mongodb 蒙戈 $group 与 $project

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35176641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:38:25  来源:igfitidea点击:

Mongo $group with $project

mongodbaggregation-framework

提问by Prashant Thorat

I am trying to get keyword count along with parentId, categioryIdand llcId. My db is

我正在尝试获取关键字计数以及parentId,categioryIdllcId。我的数据库是

{
    "_id" : ObjectId("5673f5b1e4b0822f6f0a5b89"),
    "keyword" : "electronic content management system",
    "llcId" : "CL1K9B",
    "categoryId" : "CL1K8V",
    "parentId" : "CL1K8V",

}

I tried $projectwith $group

我试着$project$group

db.keyword.aggregate([
    {
        $group: {
            _id: "$llcId",
            total: {$sum: 1},
        }
    },
    {
        $project: {
            categoryId: 1, total: 1
        }
    }
])

And it gives me a result like

它给了我一个结果

{ "_id" : "CL1KJQ", "total" : 17 }
{ "_id" : "CL1KKW", "total" : 30 }

But I need actual data in result also e.g. llcId, categoryId, keyword, total. I tried to display cetgoryIdand keyword by using $projectbut it displays only _idand total. What I am missing?

但我需要实际数据结果也如llcIdcategoryIdkeywordtotal。我试图cetgoryId通过使用来显示和关键字,$project但它只显示_id和总数。我缺少什么?

回答by chridam

To get the keywordcount you'd need to group the documents by the keywordfield, then use the accumulator operator $sumto get the documents count. As for the other field values, since you are grouping all the documents by the keyword value, the best you can do to get the other fields is use the $firstoperator which returns a value from the first document for each group. Otherwise you may have to use the $pushoperator to return an array of the field values for each group:

要获得keyword计数,您需要按keyword字段对文档进行分组,然后使用累加器运算符$sum来获取文档计数。至于其他字段值,由于您是按关键字值对所有文档进行分组,因此获取其他字段的最佳方法是使用$first运算符从每个组的第一个文档中返回一个值。否则,您可能必须使用$push运算符返回每个组的字段值数组:

var pipeline = [
    {
        "$group": {
            "_id": "$keyword",
            "total": { "$sum": 1 },
            "llcId": { "$first": "$llcId"},
            "categoryId": { "$first": "$categoryId"},
            "parentId": { "$first": "$parentId"}
        }
    }
];

db.keyword.aggregate(pipeline)

回答by Sirisha

You are grouping by llcIdso it will give more than one categoryIdper llcId. If you want categoryIdas in your result, you have to write that in your group query. For example:

您正在分组,llcId因此categoryId每个llcId. 如果你想categoryId在你的结果中,你必须把它写在你的组查询中。例如:

db.keyword.aggregate([
{
    $group: {
        _id: "$llcId",
        total: {$sum: 1},
        categoryId:{$max:"$categoryId"}
    }

},
{
    $project: {
        categoryId: 1, total: 1
    }
}])