MongoDB聚合管道从数组中返回带有$ lookup的多个字段

时间:2018-10-04 13:18:28

标签: node.js mongodb express mongoose aggregation-framework

我正在尝试从Post doc获取一个createdAt排序的评论列表,在该文档中,聚合管道将用于使用displayName和profilePhoto字段在评论字段中填充评论的所有者。

发布架构:

{
  _owner: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  ...
  comments: [
    {
      _owner: { type: Schema.Types.ObjectId, ref: 'User' },
      createdAt: Number,
      body: { type: String, maxlength: 200 }
    }
  ]
}

用户架构:

{
  _id: '123abc'
  profilePhoto: String,
  displayName: String,
  ...
 }

我要返回的内容:

[
  {
    "_id": "5bb5e99e040bf10b884b9653",
    "_owner": {
        "_id": "5bb51a97fb250722d4f5d5e1",
        "profilePhoto": "https://...",
        "displayName": "displayname"
    },
    "createdAt": 1538648478544,
    "body": "Another comment"
  },
  {
    "_id": "5bb5e96686f1973274c03880",
    "_owner": {
        "_id": "5bb51a97fb250722d4f5d5e1",
        "profilePhoto": "https://...",
        "displayName": "displayname"
    },
    "createdAt": 1538648422471,
    "body": "A new comment"
  }
]

我有一些工作代码,这些代码首先从聚合获取排序的注释,然后分别填充,但我希望能够仅通过使用聚合管道来获取此查询。

当前解决方案如下:

  const postComments = await Post.aggregate([
    { $match: { _id: mongoose.Types.ObjectId(postId) } },
    { $unwind: '$comments' },
    { $limit: 50 },
    { $skip: 50 * page },
    { $sort: { 'comments.createdAt': -1 } },
    {$replaceRoot: {newRoot: '$comments'}},
    {
      $project: {
        _owner: 1,
        createdAt: 1,
        body: 1
      }
    }
  ]);

  await Post.populate(postComments, {path: 'comments._owner', select: 'profilePhoto displayName' } )

1 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

const postComments = await Post.aggregate([
  { "$match": { "_id": mongoose.Types.ObjectId(postId) } },
  { "$unwind": "$comments" },
  { "$lookup": {
    "from": "users",
    "localField": "comments._owner",
    "foreignField": "_id",
    "as": "comments._owner"
  }},
  { "$unwind": "$comments._owner" },
  { "$replaceRoot": { "newRoot": "$comments" }},
  { "$sort": { "createdAt": -1 } }
  { "$limit": 50 }
])