通过 $lookup 在 Pymongo 中的同一个集合上聚合两个项目

Agregate two items via $lookup on the same collection via Pymongo

我在同一集合“架构”下有以下数据,这是我的状态示例:

{
    "_id": "c19592b6-8110-4684-9c96-f133e08d973e",
    "display": "WAITING",
    "name": "waiting",
    "color": "#ccf0d5",
    "type": "status"
},

{
    "_id": "69e39c0c-b722-433a-aa6e-471c24211a4d",
    "display": "IN PROGRESS",
    "name": "in_progress",
    "color": "#4ddb7f",
    "type": "status"
},

{
    "_id": "59336051-776e-4f02-b988-46b3260f097c",
    "display": "APPROVED",
    "name": "approved",
    "color": "#738ace",
    "type": "status"
}

这是我的状态示例:

{
    "_id": "e351ed21-0db3-44aa-ae0c-d7b0b92b4dce",
    "index": 1,
    "display": "In Progress",
    "name": "in_progress",
    "type": "state",
    "members": ["c19592b6-8110-4684-9c96-f133e08d973e", "69e39c0c-b722-433a-aa6e-471c24211a4d"]
},

{
    "_id": "2b57768b-919e-4cba-a861-a682eeac0cd2",
    "index": 2,
    "display": "In Review",
    "name": "in_review",
    "type": "state",
    "members": ["59336051-776e-4f02-b988-46b3260f097c"]
}

最后我想得到的是:

{
        "_id": "e351ed21-0db3-44aa-ae0c-d7b0b92b4dce",
        "index": 1,
        "display": "In Progress",
        "name": "in_progress",
        "type": "state",
        "members": [{
            "_id": "c19592b6-8110-4684-9c96-f133e08d973e",
            "display": "WAITING",
            "name": "waiting",
            "color": "#ccf0d5",
            "type": "status"
        },{
            "_id": "69e39c0c-b722-433a-aa6e-471c24211a4d",
            "display": "IN PROGRESS",
            "name": "in_progress",
            "color": "#4ddb7f",
            "type": "status"
        }]
},

我看过其他类似的问题:

$MongoDB $lookup foreach element in array on the same collection

但每个案例都略有不同,老实说,我无法完全理解 $lookup。感谢您的帮助。

db.c2.aggregate([
  {
    $match: {
      _id: "e351ed21-0db3-44aa-ae0c-d7b0b92b4dce"
    }
  },
  {
    $unwind: "$members"
  },
  {
    $lookup: {
      from: "c1",
      localField: "members",
      foreignField: "_id",
      as: "members"
    }
  },
  {
    $group: {
      _id: "$_id",
      index: { $first: "$index" },
      display: { $first: "$display" },
      name: { $first: "$name" },
      type: { $first: "$type" },
      members: { $push: "$members" }
    }
  }
])

mongoplayground


db.schema.aggregate([
  {
    $match: { type: "state" }
  },
  {
    $unwind: "$members"
  },
  {
    $lookup: {
      from: "schema",
      localField: "members",
      foreignField: "_id",
      as: "members"
    }
  },
  {
    $group: {
      _id: "$_id",
      index: { $first: "$index" },
      name: { $first: "$name" },
      display: { $first: "$display" },
      type: { $first: "$type" },
      members: { $push: { $first: "$members" } }
    }
  }
])

mongoplayground