【问题标题】:Mongo DB - Group status and get total count using aggregationMongodb - 使用聚合对状态进行分组并获取总数
【发布时间】:2018-06-08 08:19:26
【问题描述】:

我创建了一个收藏帖子,并添加了如下所示的文档。

[{
    "title" : "MongoDB-Overview", 
    "status" : "created",
    "postBy" : "sukesh"
}, {
    "title" : "MongoDB-Collection", 
    "status" : "created",
    "postBy" : "sukesh"
}, {
    "title" : "MongoDB-Document", 
    "status" : "approved",
    "postBy" : "sukesh"
}, {
    "title" : "MongoDB-Database", 
    "status" : "approved_pending",
    "postBy" : "ramesh"
}, {
    "title" : "MongoDB-Query", 
    "status" : "deleted",
    "postBy" : "suresh"
}]

我需要使用会计数的聚合函数,
1. 分配给特定人的帖子总数(这里只有 sukesh),以及
2. 状态总数,如果状态没有赋值则返回0。
如下所示。

{
   "postby": "sukesh"
   "totalPost": 4,
   "status": {
      "created": 2
      "approved": 1,
      "approved_pending": 0,
      "deleted": 1
    }       
}

请帮我解决。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    我不认为这完全可以如你所愿,但如果你能用这个,你可以试试:

    db.collection.aggregate([
    {
      $group: {
        _id: "$postBy",
        count: { $sum: 1},
        status: { $push: "$status"}
      }
    },
    { $unwind: "$status"},
    {
      $group: {
        _id: { "postby": "$_id", status: "$status" },
        scount: { $sum: 1},
        count: {$first: "$count"}
      }
    }, 
    {$group: {
            _id: "$_id.postby",  
            total: {$first: "$count"},
            status: {$push:  { type: "$_id.status", count: "$scount" }},
    }},
    {
      $project: {
        _id: 0,
        postby: "$_id",
        totalPost: "$total",
        status: 1
      } 
    }
    ])
    

    【讨论】:

    • 感谢 Alex 编写了完美的聚合函数并做出如此迅速的反应,让我很开心。
    • 没问题的朋友!
    猜你喜欢
    • 2020-11-16
    • 2023-01-20
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2018-10-28
    相关资源
    最近更新 更多