$ push与$ group在mongo聚合中

时间:2018-07-28 06:57:25

标签: mongodb mongodb-query aggregation-framework

我写了这个查询,但它不完全是我想要如何使用推算符获得预期的结果- 不能将push与addFields和项目管道一起使用。

db.getCollection("event").aggregate([ {$match:{"name":"Add            
to Cart"}}, {$group:{"_id":"browser",count:{$sum:1}}}]);

输出:

{_id:chrome.count:3}
{_id:firefox,count:1}
{_id:edge,count:1}

期望输出:

{
browser:[
{name:"chrome",count:3},
{name:"firefox",count:1}, 
{name:"egde",count:1}
]
}

我的收藏集:

{
_id:1,
 name:"Add to Cart"
"browser":"chrome"
}
{
_id:2,
name:"Searched",
"browser":"chrome"
}
{
_id:3,
name:"Add To Cart",
"browser":"edge"
}
{
_id:4,
name:"Item View",
"browser":"chrome"
}
{
_id:5,
name:"Add To Cart",
"browser":"Firefox"
}

1 个答案:

答案 0 :(得分:2)

您需要在这里再使用一个$group阶段

db.collection.aggregate([
  { "$group": {
    "_id": "$browser",
    "count": { "$sum": 1 }
  }},
  { "$group": {
    "_id": null,
    "browser": {
      "$push": {
        "name": "$_id",
        "count": "$count"
      }
    }
  }},
  { "$project": { "_id": 0 }}
])