我有一个这样的数据集
{
"_id" : ObjectId("5a1414430b4215041c768f50"),
"slug" : [
"a", "b", "c"
]
},
{
"_id" : ObjectId("5a1414430b4215041c768f51"),
"slug" : [
"a", "d", "e"
]
},
{
"_id" : ObjectId("5a1414430b4215041c768f52"),
"slug" : [
"b", "b", "f"
]
},
{
"_id" : ObjectId("5a1414430b4215041c768f53"),
"slug" : [
"g", "h", "b"
]
}
所以在这里,数组存储字符串。现在我想计算在整个数据集上,slug 的 Values 重复了多少次。例如:在我的数据库查询之后,期望的结果将是这样的
a = 2, b = 4, c = 1, d = 1, e = 1, f = 1, g = 1, h = 1
我正在使用聚合来执行此类任务,但无法准确获得所需的结果。 我的查询是
Message.aggregate([
{"$project": {"slug":1}},
{"$unwind":"$slug"},
{"$group": {"_id":{"_id":"$_id", "slug":"$slug"}, "count":{"$sum":1}}},
{"$match": {"count":{"$gt":1}}},
{"$group": {"_id": "$_id._id", "slug":{"$addToSet":"$_id.slug"}}}
]);
此查询仅在找到任何字符串时才返回数据。 请指导我哪里做错了。任何帮助将不胜感激。
最佳答案
你已经自己做到了,或者说你已经达到了你所要求的结果。只需使用以下查询即可获得所需的结果
db.Message.aggregate([
{$unwind:"$slug"},
{$group:{"_id":"$slug", "count":{"$sum":1}}}
]);
相关示例文档的结果如下所示
{ "_id" : "h", "count" : 1 }
{ "_id" : "g", "count" : 1 }
{ "_id" : "f", "count" : 1 }
{ "_id" : "e", "count" : 1 }
{ "_id" : "b", "count" : 4 }
{ "_id" : "d", "count" : 1 }
{ "_id" : "c", "count" : 1 }
{ "_id" : "a", "count" : 2 }
要使结果以排序方式打印,请使用 $sort
db.Message.aggregate([
{$unwind:"$slug"},
{$group:{"_id":"$slug", "count":{"$sum":1}}},
{$sort:{"_id":1}}
]);
我们对“_id”使用升序,排序结果为
{ "_id" : "a", "count" : 2 }
{ "_id" : "b", "count" : 4 }
{ "_id" : "c", "count" : 1 }
{ "_id" : "d", "count" : 1 }
{ "_id" : "e", "count" : 1 }
{ "_id" : "f", "count" : 1 }
{ "_id" : "g", "count" : 1 }
{ "_id" : "h", "count" : 1 }
Is there any solution to get my slug value to custom field rather than under _id. Like
{ "slugname" : "a", "count" : 2 }
instead of{ "_id" : "a", "count" : 2 }
这可以通过添加 $project 来完成到现有的查询
_id:0 - 将其抑制到下一阶段
slugname :"$_id"- 将 _id 的值添加到 slugname
db.Message.aggregate([
{$unwind:"$slug"},
{$group:{"_id":"$slug", "count":{"$sum":1}}},
{$sort:{"_id":1}},
{$project: {_id:0, slugname :"$_id", count:"$count"}}
]);
最终结果
{ "slugname" : "a", "count" : 2 }
{ "slugname" : "b", "count" : 4 }
{ "slugname" : "c", "count" : 1 }
{ "slugname" : "d", "count" : 1 }
{ "slugname" : "e", "count" : 1 }
{ "slugname" : "f", "count" : 1 }
{ "slugname" : "g", "count" : 1 }
{ "slugname" : "h", "count" : 1 }
关于node.js - 数组 mongodb 上出现值的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47428527/