我正在尝试与parentId
,categioryId
和llcId
一起获取关键字计数。
我的数据库是
{
"_id" : ObjectId("5673f5b1e4b0822f6f0a5b89"),
"keyword" : "electronic content management system",
"llcId" : "CL1K9B",
"categoryId" : "CL1K8V",
"parentId" : "CL1K8V",
}
我使用$project
$group
db.keyword.aggregate([
{
$group: {
_id: "$llcId",
total: {$sum: 1},
}
},
{
$project: {
categoryId: 1, total: 1
}
}
])
它给了我一个像
的结果{ "_id" : "CL1KJQ", "total" : 17 }
{ "_id" : "CL1KKW", "total" : 30 }
但我需要结果中的实际数据,例如llcId
,categoryId
,keyword
,total
。我尝试使用cetgoryId
显示$project
和关键字,但它只显示_id
和总计。{我缺少什么?
答案 0 :(得分:32)
要获得keyword
计数,您需要按var pipeline = [
{
"$group": {
"_id": "$keyword",
"total": { "$sum": 1 },
"llcId": { "$first": "$llcId"},
"categoryId": { "$first": "$categoryId"},
"parentId": { "$first": "$parentId"}
}
}
];
db.keyword.aggregate(pipeline)
字段对文档进行分组,然后使用累加器运算符 $sum
来获取文档计数。至于其他字段值,由于您要按关键字值对所有文档进行分组,因此您可以使用 $first
运算符来获取其他字段的最佳值。每组的第一份文件。否则,您可能必须使用 $push
运算符来返回每个组的字段值数组:
myRichTextBox.BorderThickness = new Thickness(3,3,0,3);
答案 1 :(得分:3)
您按llcId
进行分组,因此每个categoryId
会提供多个llcId
。
如果您希望在结果中使用categoryId
,则必须在组查询中写入。例如:
db.keyword.aggregate([
{
$group: {
_id: "$llcId",
total: {$sum: 1},
categoryId:{$max:"$categoryId"}
}
},
{
$project: {
categoryId: 1, total: 1
}
}])