gpt4 book ai didi

mongodb将重复文档分组到一个数组

转载 作者:行者123 更新时间:2023-12-04 11:02:03 26 4
gpt4 key购买 nike

我试图将特定键的所有文档组织到一个数组中。如果任何其他参数不同,我不想一次又一次地获得相同的关键元素。
样本文件:-

{
name:"sweta",
age:23
address:india,
hobby:singing
},
{
name:"john",
age:24
address:germany,
hobby:singing
},
{
name:"peter",
age:24
address:india,
hobby:dancing
},
{
name:"marry",
age:23
address:india,
hobby:singing
},

我试过什么?
return db.aggregate([
{
$match:{age:23}
},
{
"$group":{
"_id": {"age":"$age"},
}
},
{
"$group":{
"_id":"$_id.age",
"name":{ $first: "$_id.name"},
"address":{ $first: "$_id.address"},
"hobby":{ $first: "$_id.hobby"},
}
])

基本上以这种格式分组减少了最大的业务逻辑。

预期答案 =
  [
{
"23":[
{name:"sweta",address:india,hobby:singing},
{name:"marry",address:india,hobby:singing},
]
},
{
"24":[
{name:"john",address:germany,hobby:singing},
{name:"peter",address:france,hobby:singing}
]
}

]

任何人都知道如何得到这个?

最佳答案

你可以试试这个

db.getCollection('Test').aggregate([
{ $group: { _id: "$age" ,
data: { $push: {"name":"$name", "address":"$address", "hobby":"$hobby"}},
}
},
{ "$replaceRoot": {
"newRoot": {
"$arrayToObject": {
"$concatArrays": [
[
{ "k": {$toString: "$_id"}, "v": "$data" }
]
]
}
}
}}
])

结果:
[ {
"24" : [
{ "name" : "john", "address" : "germany", "hobby" : "singing" },
{ "name" : "peter", "address" : "india", "hobby" : "dancing" }
]
},
{
"23" : [
{ "name" : "sweta", "address" : "india", "hobby" : "singing" },
{ "name" : "marry", "address" : "india", "hobby" : "singing" }
]
}]

关于mongodb将重复文档分组到一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58745471/

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