gpt4 book ai didi

java - Mongodb 获取唯一值的计数

转载 作者:行者123 更新时间:2023-12-01 08:52:48 24 4
gpt4 key购买 nike

我有这样的数据收集

{
"_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}]} 

提前致谢

最佳答案

所以这个想法是$group几次,首先在对usercontact进行分组时计算计数,并对进行其他分组>user 推送联系人计数。我已经包含了需要更改的查询区域

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
}]
}

关于java - Mongodb 获取唯一值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42276617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com