填充 obj 数组的字段查找

Populate fields lookup of an obj array

里面Element我有一个associations的数组,这些关联是collection.

这个collection是由很多键组成的obj,在这些键中有引用其他collection的元素(objobj2) 我想填充这两个 collections.

但我无法理解它是如何做到的,甚至无法尝试尽可能少地执行操作。

据我了解,您可能需要使用 $unwind

元素:

{
_id: "",
element: "",
associations: [],
updatedAt: "",
createdAt: ""
}

协会:

{
_id: "",
code: "",
obj: "5s5s55s5d555dff", //populate - Schema.Types.ObjectId - ref: 'objGroup'
obj2: "5f5e5e5e5d5d5d5", //populate - Schema.Types.ObjectId - ref: 'obj2Group'
updatedAt: "",
createdAt: ""
}

在元素中:

aggregate.push({
    $lookup: {
      from: 'associations',
      let: { cId: '$_id' },
      pipeline: [
        { $match: { $expr: { $eq: ['$code', '$$cId'] } } },
        { $match: { $or: getTimeRange(from, to) } }
      ],
      as: 'associations'
    }
  })

您可以在查找管道中使用嵌套查找,

db.element.aggregate([
  {
    $lookup: {
      from: "associations",
      let: { cId: "$_id" },
      pipeline: [
        { $match: { $expr: { $eq: ["$code", "$$cId"] } } },
        { $match: { $or: getTimeRange(from, to) } },
        {
          $lookup: {
            from: "objCollection",
            localField: "obj",
            foreignField: "_id",
            as: "obj"
          }
        },
        { $unwind: "$obj" },
        {
          $lookup: {
            from: "obj2Collection",
            localField: "obj2",
            foreignField: "_id",
            as: "obj2"
          }
        },
        { $unwind: "$obj2" }
      ],
      as: "associations"
    }
  }
])