You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MongoDB聚合得到的子文档最小status值更新至父文档?

问题描述

集合中的文档结构如下:

[
  {
    "_id": ObjectId("62f45101c6b6654eafcf8859"),
    "parentId": null,
    "status": 1
  },
  {
    "_id": ObjectId("62f45e6c74f4f1d1cf4bc73a"),
    "parentId": ObjectId("62f45101c6b6654eafcf8859"),
    "status": 4
  },
  {
    "_id": ObjectId("62f45e6c74f4f1d1cf4bc73b"),
    "parentId": ObjectId("62f45101c6b6654eafcf8859"),
    "status": 3
  }
]

需要将parentId为null的父文档的status字段更新为其子文档status的最小值(即min(4,3)=3)。

已通过聚合管道查询出子文档的最小status:

db.collName.aggregate([
    {
        $match: {
            parentId: ObjectId("62f45101c6b6654eafcf8859")
        }
    },
    {
        $group: {
            _id: ObjectId("62f45101c6b6654eafcf8859"),
            status: {
                $min: "$status"
            }
        }
    }
])

返回结果:

{ "_id" : ObjectId("62f45101c6b6654eafcf8859"), "status" : 3 }

但不清楚如何将该结果应用到父文档的更新操作中。

解决方案

方法1:聚合管道直接更新(MongoDB 4.2+适用)

可以直接在updateOne中嵌入聚合管道,一步完成关联子文档、计算最小值、更新父文档的操作:

db.collName.updateOne(
  { parentId: null }, // 匹配目标父文档
  [
    {
      $lookup: {
        from: "collName", // 关联当前集合
        localField: "_id",
        foreignField: "parentId",
        as: "children"
      }
    },
    {
      $set: {
        status: { $min: "$children.status" } // 提取子文档status的最小值并更新
      }
    }
  ]
)

方法2:先获取聚合结果再更新(低版本MongoDB适用)

如果你的MongoDB版本低于4.2,可分两步执行:先通过聚合查询拿到最小status值,再执行更新:

// 执行聚合查询,获取子文档的最小status
const aggResult = db.collName.aggregate([
  { $match: { parentId: ObjectId("62f45101c6b6654eafcf8859") } },
  { $group: { _id: null, minStatus: { $min: "$status" } } }
]).toArray()[0];

// 若查询到结果,更新父文档
if (aggResult) {
  db.collName.updateOne(
    { _id: ObjectId("62f45101c6b6654eafcf8859") },
    { $set: { status: aggResult.minStatus } }
  );
}

内容的提问来源于stack exchange,提问作者zx01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 02:06:35