Database MongoDB:列出用户名和他们收到的回复数量

Database MongoDB:列出用户名和他们收到的回复数量,database,mongodb,mongodb-query,aggregation-framework,aggregate,Database,Mongodb,Mongodb Query,Aggregation Framework,Aggregate,我在mongoDB中建立了一个集合,其中包含来自一个虚构的社交媒体平台的用户的示例评论,格式如下: { "_id" : ObjectId("5aa58936c4214f42f4c666b8"), "id" : "85", "user_name": "Alex4Ever", "text" : "This is

我在mongoDB中建立了一个集合,其中包含来自一个虚构的社交媒体平台的用户的示例评论,格式如下:

{
     "_id" : ObjectId("5aa58936c4214f42f4c666b8"),
     "id" : "85",
     "user_name": "Alex4Ever",
     "text" : "This is a comment",
     "in_reply_to_user_name": "SamLad"
},
{
     "_id" : ObjectId("5aa58935c4214f42f4c66608"),
     "id" : "86",
     "user_name": "SamLad",
     "text" : "I am inevitable",
     "in_reply_to_user_name": null
},
{
     "_id" : ObjectId("5aa588e4c4214f42f4c63caa"),
     "id" : "87",
     "user_name": "HewwoKitty",
     "text" : "What is grief, if not love persevering?",
     "in_reply_to_user_name": "Alex4Ever"
} //There are more, but for testing purposes, I only use these 3 for now.
我必须在MongoDB中提出一个查询,列出文件中的所有用户以及他们收到的回复量。因此,在上述文件的示例位中,输出应如下所示:

"_id": "Alex4Ever", "replyCount" : 1,  //HewwoKitty replied to Alex4Ever
"_id": "SamLad", "replyCount" : 1,     //Alex4Ever replied to SamLad
"_id": "HewwoKitty", "replyCount" : 0, //No one replied to HewwoKitty
我尝试这样做:

db.comments.aggregate([
                      {$match:{"in_reply_to_user_name":{"$exists":true, "$ne":null}}},
                      {$group: { _id: "$in_reply_to_user_name", replyCount:{$sum: 1}}}, 
                      {$sort:{replyCount: -1}}
                     ]).pretty()
但是,我只得到非零值,即我没有得到
0
replyCount
HewwoKitty
。有没有办法打印所有3行,包括0条回复的行?

Demo-

使用和创建自连接以获取用户的所有回复,并使用获取回复的计数,然后在用户名上添加回复

提取replyCount,从组中获取值

db.collection.aggregate([
  {
    "$match": {
      "in_reply_to_user_name": { "$exists": true }
    }
  },
  {
    "$lookup": {
      "from": "collection",
      "localField": "user_name",
      "foreignField": "in_reply_to_user_name",
      "as": "replies"
    }
  },
  {
    "$project": {
      "user_name": 1,
      "replyCount": { "$size": "$replies" }
    }
  },
  {
    "$group": {
      "_id": "$user_name",
      "replyCount": {  "$first": "$replyCount" }
    }
  }
])
演示-

使用和创建自连接以获取用户的所有回复,并使用获取回复的计数,然后在用户名上添加回复

提取replyCount,从组中获取值

db.collection.aggregate([
  {
    "$match": {
      "in_reply_to_user_name": { "$exists": true }
    }
  },
  {
    "$lookup": {
      "from": "collection",
      "localField": "user_name",
      "foreignField": "in_reply_to_user_name",
      "as": "replies"
    }
  },
  {
    "$project": {
      "user_name": 1,
      "replyCount": { "$size": "$replies" }
    }
  },
  {
    "$group": {
      "_id": "$user_name",
      "replyCount": {  "$first": "$replyCount" }
    }
  }
])

非常感谢您的回答。:)非常感谢您的回答。:)