使用mongodb聚合groupby

时间:2018-12-10 09:14:59

标签: mongodb group-by aggregate

db.getCollection('dbName').aggregate(
{$match: {"Request":"request"}},
{$project : {"PageResult":1,"ProductFilter":1,"BreadCrumbs":1,"ShowCaseHtml":1}},
{$unwind: "$PageResult"},
{$match: { $and:[ 
                {"PageResult.Brand":{$in:[/b1/i,/b2/i]}}
             ]}},
{$group: {"_id": {"Request":"$Request",
    "ProductFilter":"$ProductFilter",
    "BreadCrumbs":"$BreadCrumbs",
    "ShowCaseHtml":"$ShowCaseHtml"},
    "PageResult": {$push : "$PageResult"}}},
{$project : {"PageResult.CategoryID":1}}
)

查询结果,如:

PageResult" : [ 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60006410"
        }, 
        {
            "CategoryID" : "60005202"
        }, 
        {
            "CategoryID" : "60005202"
        }, 
        {
            "CategoryID" : "60005202"
        }, 
        {
            "CategoryID" : "60005202"
        }, 
        {
            "CategoryID" : "60005202"
        }, 
        {
            "CategoryID" : "60005202"
        }
    ]

我正在尝试将PageResult与CategoryID分组,因此我将以下行添加到上述查询中:

{$unwind: "$PageResult"},
{ $group : {_id : "$PageResult.CategoryID", count : {$sum : 1} } }

但这给了我

{
"_id" : "60005202",
"count" : 6.0
}

我使用$ group错误吗,不是结果应该是

 {
"_id" : "60006410",
"count" : 10.0
}, 
{
"_id" : "60005202",
"count" : 6.0
}

1 个答案:

答案 0 :(得分:0)

我发现了为什么会看到这种结果,几天前,我在C:\ Users \ username.3T \ robo-3t \ 1.1.1 \ robo3t.json文件中更改了batchsize(batchsize:1),正常情况下,我每次更改默认值都看到1个结果,我认为默认值为50,所以这意味着我的代码工作正常。