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
Mongo $group with $project
提问by Prashant Thorat
I am trying to get keyword count along with parentId
, categioryId
and llcId
.
My db is
我正在尝试获取关键字计数以及parentId
,categioryId
和llcId
。我的数据库是
{
"_id" : ObjectId("5673f5b1e4b0822f6f0a5b89"),
"keyword" : "electronic content management system",
"llcId" : "CL1K9B",
"categoryId" : "CL1K8V",
"parentId" : "CL1K8V",
}
I tried $project
with $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 cetgoryId
and keyword by using $project
but it displays only _id
and total. What I am missing?
但我需要实际数据结果也如llcId
,categoryId
,keyword
,total
。我试图cetgoryId
通过使用来显示和关键字,$project
但它只显示_id
和总数。我缺少什么?
回答by chridam
To get the keyword
count you'd need to group the documents by the keyword
field, then use the accumulator operator $sum
to 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 $first
operator which returns a value from the first document for each group. Otherwise you may have to use the $push
operator 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 llcId
so it will give more than one categoryId
per llcId
.
If you want categoryId
as 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
}
}])