MongoDB聚合框架和嵌套的$lookup

3
我是一个有用的助手,可以为您翻译文本。以下是您需要翻译的内容:

我正在尝试使用MongoDB聚合框架进行嵌套数据查询,但遇到了一些问题。

这是我拥有的初始数据:

[
  {
    _id: ObjectId('123'),
    profileId: ObjectId('456')
  },
  // ...other documents
]

我将这个聚合管道应用到它上,以便通过使用profileId字段填充profile字段:
MyModel.aggregate([
  {
    $lookup: {
      from: 'profiles',
      localField: 'profileId',
      foreignField: '_id',
      as: 'profile'
    }
  },
  {
    $project: {
      profile: {
        $arrayElemAt: [ '$profile', 0 ]
      },
      profileId: 1,
    }
  },
]

这是结果:

[
  {
    _id: ObjectId('123'),
    profileId: ObjectId('456'),
    profile: {
      grades: [
        ObjectId('...'),
        ObjectId('...')
      ]
      // ... other props
    }
  }
  // ...other documents
]

现在我通过添加$lookup来扩展管道,以填充每个profile文档中的成绩:

MyModel.aggregate([
  {
    $lookup: {
      from: 'profiles',
      localField: 'profileId',
      foreignField: '_id',
      as: 'profile'
    }
  },
  {
    $project: {
      profile: {
        $arrayElemAt: [ '$profile', 0 ]
      },
      profileId: 1,
    }
  },
  {
    $lookup: {
      from: 'profile-grades',
      localField: 'profile._id',
      foreignField: 'profile',
      as: 'profile.grades'
    }
  }
]

这是目前的结果:
[
  {
    _id: ObjectId('123'),
    profileId: ObjectId('456'),
    profile: {
      grades: [
        {
          studyLocationId: ObjectId('789'),
          // ... other props
        },
        // ... other grades
      ]
    }
  }
  // ...other documents
]

我无法完成的最后一步是在 grades 数组中填充每个 studyLocation
期望的结果为:
[
  {
    _id: ObjectId('123'),
    profileId: ObjectId('456'),
    profile: {
      grades: [
        {
          studyLocationId: ObjectId('789'),
          studyLocation: {
            _id: ObjectId('...'),
            // other props
          },
        },
        // ... other grades
      ]
    }
  }
  // ...
]

我曾经尝试添加一个$lookup阶段,但是没有成功:

  {
    $lookup: {
      from: 'study-locations',
      localField: 'profile.grades.studyLocationId',
      foreignField: '_id',
      as: 'profile.grades.studyLocation'
    }
  }

这只是简单地返回:
grades: {
   studyLocation: []
}

我应该如何做?这是否可能实现?谢谢!

1个回答

1
如果您正在使用mongodb3.4,那么这将起作用,对于之前的版本,您需要在成绩上使用展开运算符。

抱歉,我忘记说明了:我正在使用v3.4.5版本。 - Alerosa
然后,您必须在“profile.grades”上使用“$unwind”才能使用“$lookup”。 - Shubham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接