mongodb 包含特定字段的聚合查询

mongodb aggregation query to include a specific field

我有一个 mongodb 架构,看起来像

{
post_id: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: "Post"
},
comment_by: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: "User"
},
comment: {
    type: String,
    required: true
},
parent_comment_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Comment"
},
is_deleted: {
    type: Boolean,
    default: false
}

}

我想对评论进行分组 他们有共同的“parent_comment_id”,但我也想包括 “id”为“parent_comment_id”的文档。 这是我写的查询

var comments = await Comment.aggregate([
        {
            "$match": {
                post_id: mongoose.Types.ObjectId(post_id)
            }
        },
        {
            "$group": {
                _id: `$parent_comment_id`,
                replies: { "$count": {} }
            }
        }
    ])

结果是

{ _id: new ObjectId("6278e11fa7887263e6e6fada"), replies: 3 },
{ _id: new ObjectId("6278fb9f6a8d30c46eb53a84"), replies: 5 },
{ _id: null, replies: 2 }

我想要的结果

{ _id: new ObjectId("6278e11fa7887263e6e6fada"), replies: 3 , comment : <comment>},
{ _id: new ObjectId("6278fb9f6a8d30c46eb53a84"), replies: 5 , comment : <comment>},

欢迎 heeya joshi!

你可以这样做:

  db.collection.aggregate([
      {
        $match: {post_id: mongoose.Types.ObjectId(post_id)}
      },
      {
        $addFields: {
          parent_comment_id: {$ifNull: ["$parent_comment_id", "$_id"]}
        }
      },
      {
        $group: {
          _id: "$parent_comment_id",
          "comment": {
            $push: {
              $cond: [
                {$eq: ["$parent_comment_id", "$_id"]},
                "$comment",
                "$$REMOVE"
              ]
            }
          },
          replies: {"$count": {}}
        }
      },
      {
        $project: {
          comment: {$arrayElemAt: ["$comment", 0]},
          replies: 1
        }
      }
    ])

如你所见here

在您的 $match 之后,addFieldsparent_comment_id 添加到 parents 本身。然后 $group 只为 parents.

保留注释