我正在尝试建立一个可以告诉我颜色发生次数和与每种颜色对应的实体次数的小组。
我写了一个查询,但是由于我想放松,这给了我两倍的计数。
我的查询:
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
}
]
}
请帮助!。