MongoDB查询以获取特定组的数组值计数
我正在尝试实现一个组,该组告诉我颜色的出现计数和对应于每个颜色的实体计数 我写了一个查询,但这是给我两倍的计数,因为我想放松 我的问题是:MongoDB查询以获取特定组的数组值计数,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我正在尝试实现一个组,该组告诉我颜色的出现计数和对应于每个颜色的实体计数 我写了一个查询,但这是给我两倍的计数,因为我想放松 我的问题是: db.message.aggregate([ {$unwind: '$entities'}, { "$group": { "_id": { "color": "$color", "entities" :"$entities" }, "count": { "$sum": 1 } }}, { "$group
db.message.aggregate([
{$unwind: '$entities'},
{ "$group": {
"_id": {
"color": "$color",
"entities" :"$entities"
},
"count": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.color",
"count": { "$sum": "$count" },
"entities": {
"$push": {
"entity": "$_id.entities",
"count": "$count"
},
}
}}
])
数据库消息数据:
{
"_id" : ObjectId("5c55f99abf6dc481ccfa7f67"),
"color" : "Red",
"channel" : "google",
"content" : "red color",
"entities" : [
"a",
"b"
]
},
{
"_id" : ObjectId("5c57f0a0bf6dc44424e8d371"),
"color" : "Red",
"channel" : "google",
"content" : "red color",
"entities" : [
"a",
"b"
]
},{
"_id" : ObjectId("5c5947a4bf6dc462603d87da"),
"color" : "Blue",
"channel" : "google",
"content" : "yo yo",
"entities" : [
"a",
"b"
]
},
{
"_id" : ObjectId("5c6151b9bf6dc4bee8dac8c9"),
"color" : "Blue",
"handle" : "IBM",
"channel" : "twitter",
"content" : "yo yo",
"entities" : [
"a",
"b",
"c"
]
}
(已编辑)我期待以下输出:
{
"color" : "Red",
"count" : 2,
"entities" : [
{
"entity" : "a",
"count" : 2
},
{
"entity" : "b",
"count" : 2
}
]
},
{
"color" : "Blue",
"count" : 2,
"entities" : [
{
"entity" : "c",
"count" : 1
},
{
"entity" : "b",
"count" : 2
},
{
"entity" : "a",
"count" : 2
}
]
}
请帮忙
分类
不是数组字段。你如何使用$unwind
呢?是的,即使我删除了它也没有什么区别。你也可以发布预期的输出吗?我已经为我预期的输出编辑了我的问题,谢谢。分类
不是数组字段。你如何使用$unwind
呢?是的,即使我删除了它也没有什么区别。你能发布预期的输出吗?我已经为我预期的输出编辑了我的问题,谢谢。