我有这样的数据收集
{
"_id" : ObjectId("58a42914eef0ba24b49cbf3a"),
"user" : "111",
"contact" : "555"
},
{
"_id" : ObjectId("58a42922eef0ba24b49cbf3b"),
"user" : "111",
"contact" : "666"
},
{
"_id" : ObjectId("58a4292deef0ba24b49cbf3c"),
"user" : "111",
"contact" : "666"
},
{
"_id" : ObjectId("58a42934eef0ba24b49cbf3d"),
"user" : "222",
"contact" : "666"
},
{
"_id" : ObjectId("58a42938eef0ba24b49cbf3e"),
"user" : "222",
"contact" : "777"
},
{
"_id" : ObjectId("58a4293eeef0ba24b49cbf3f"),
"user" : "222",
"contact" : "888"
},
{
"_id" : ObjectId("58a4293feef0ba24b49cbf40"),
"user" : "222",
"contact" : "888"
},
{
"_id" : ObjectId("58a42941eef0ba24b49cbf41"),
"user" : "222",
"contact" : "888"
},
{
"_id" : ObjectId("58a42947eef0ba24b49cbf42"),
"user" : "333",
"contact" : "888"
},
{
"_id" : ObjectId("58a4294ceef0ba24b49cbf43"),
"user" : "333",
"contact" : "666"
},
我是否可以在每个用户中获得结果列表联系人及其计数,如Java中所示?
{user:user_name,data[contact:count]}
因此结果应如下所示,每个用户都有一个联系人列表
{user:111,contact:[{555:1},{666:2}]},{user:222,contact:[{666:1},{777:1},{888:3}]},{user:333,contact:[{888:1},{666:1}]}
提前致谢
答案 0 :(得分:1)
所以这个想法是$group
几次,首先在user
和contact
上进行分组时计算次数,然后在user
上进行另一次分组以推送contact
}和count
。我已经包含了需要更改的查询区域
db.data.aggregate([{
$group: {
_id: {
user: "$user",
contact: "$contact"
},
count: {
$sum: 1
}
}
}, {
$group: {
_id: "$_id.user",
uniqueIds: {
$push: {
contact: "$_id.contact",
count: "$count"
}
}
}
}])
您无法以您想要的方式获得回复。你总是拥有密钥和价值对。
示例回复:
{
"_id": "111",
"uniqueIds": [{
"contact": "555",
"count": 1
}, {
"contact": "666",
"count": 2
}]
}