是否有任何占位符值可用于 MongoDB 聚合查找,以在 object 的 object 中找到正确的字段?

Is there any placeholder value that can be used in a MongoDB aggregation lookup, to find the right field in an object of objects?

我有两个 collection,第一个有第二个 collection 的外键。现在我想聚合第二个collection的匹配数据。问题是,我不知道如何正确定义 localField 的路径,因为它位于 object 的 object 中。 它将在某个时候更改为 object 的数组,但现在我必须处理它。 collection 结构如下所示:

collection一个

{
  _id: ObjectId('...'),
  groups: {
    '1': {
      things: [{
        id: xyz,
        foreignId: ObjectID('001') // id of collectionTwo
      }]
    },
    '2': {
      things: [{
        id: zyx,
        foreignId: ObjectId('001') // id of collectionTwo
      }]
    },
  }
}

collection两个

{
  _id: ObjectID('001').
  ...
}

我通读了文档并在此处和其他地方进行了搜索,但没有找到任何匹配的案例。 对于我知道的数组,我不必指定数组中的实际位置。因此,如果 groups 也是一个 object 数组,我可以像这样使用点运算符:

collectionOne.aggregate([
      {$match: {_id, ObjectID('...')},
      {$lookup: {
        from: 'collectionTwo',
        localField: 'groups.things.foreignId',
        foreignField: '_id',
        as: 'aggregatedThings'
      }},
    ])

所以我想将 localField 设置为匹配 groups 中每个 object 的路径。像这样,其中 $ 是每个键的占位符:

collectionOne.aggregate([
      {$match: {_id, ObjectID('...')},
      {$lookup: {
        from: 'collectionTwo',
        localField: 'groups.$.things.foreignId',
        foreignField: '_id',
        as: 'aggregatedThings'
      }},
    ])

我希望我的问题很清楚。 感谢任何帮助。 :)

我找到了解决方法。

collectionOne.aggregate([
      {$match: {_id, ObjectID('...')},
      { '$addFields': {
        'groupsArray': { $objectToArray: '$groups' }
      }},
      {$lookup: {
        from: 'collectionTwo',
        localField: 'groupsArray.v.things.foreignId',
        foreignField: '_id',
        as: 'aggregatedThings'
      }},
    ])

使用 $objectToArray 将对象转换为数组对我有用。