首页 文章

使用mongodb聚合组

提问于
浏览
0
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

    我发现为什么我看到这种结果,几天前我在C:\ Users \ username.3T \ robo-3t \ 1.1.1 \ robo3t.json文件中更改了batchsize(batchsize:1),所以这是正常的我一直看到1个结果我默认改为50,我认为这意味着我的代码工作得很好 .

相关问题