查找 Objects 数组

lookup on array of Objects

如何通过引用 ID 和其他属性使用 object 进行查找。

集合A

{
  _id: ObjectId("6013859ba0c3120034d08bfa"),
  name: "A1",
  refs:[
   {id: ObjectId("6013859ba0c3120034d08bfb"), text: "ABC"},
   {id: ObjectId("6013859ba0c3120034d08bfc"), text: "DEF"}
  ]
}

收藏B

{
  _id: ObjectId("6013859ba0c3120034d08bfb"),
  name: "B1"
}

{
  _id: ObjectId("6013859ba0c3120034d08bfc"),
  name: "B2"
}

预期结果

{
  _id: ObjectId("6013859ba0c3120034d08bfa"),
  name: 'A1',
  refs:[
   {id: ObjectId("6013859ba0c3120034d08bfb"), name: "B1", text: "ABC"},
   {id: ObjectId("6013859ba0c3120034d08bfc"), name: "B2", text: "DEF"}
  ]
}
  1. $unwind - 解构 refs 数组字段。
  2. $lookup - 加入 collectionA (refs.id) 与 collectionB (_id).
  3. $project - 修饰文档,通过 $first.
  4. refsB 数组中获取名字
  5. $group - 按 _id 分组并为文档生成(必填)字段。
db.collectionA.aggregate([
  {
    $unwind: "$refs"
  },
  {
    "$lookup": {
      "from": "collectionB",
      "localField": "refs.id",
      "foreignField": "_id",
      "as": "refsB"
    }
  },
  {
    $project: {
      _id: 1,
      name: 1,
      refs: {
        id: "$refs.id",
        text: "$refs.text",
        name: {
          $first: "$refsB.name"
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      name: {
        $first: "$name"
      },
      refs: {
        $push: "$refs"
      }
    }
  }
])

Sample Mongo Playground