【问题标题】:Mongodb aggregate pipeline to return multiple fields with $lookup from arrayMongodb聚合管道从数组返回多个字段$lookup
【发布时间】:2018-10-05 00:29:21
【问题描述】:

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

发布架构:

{
  _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"
  }
]

我有一些工作代码先从聚合到排序的 cmets,然后我单独填充,但我希望能够仅通过使用聚合管道来获取此查询。

当前的解决方案如下所示:

  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' } )

【问题讨论】:

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


    【解决方案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 }
    ])
    

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 2017-10-08
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多