gpt4 book ai didi

mongodb - 聚合在 Mongodb 中的聚合

转载 作者:可可西里 更新时间:2023-11-01 10:16:04 25 4
gpt4 key购买 nike

我有一个包含印度各州、地区和村庄的文件的 mongo 集合。

{
"_id" : ObjectId("58db5a5f8f7b5013ad477564"),
"district" : "Chittor",
"state" : "Andhra Pradesh",
"village" : "Chittoor"
},
{
"_id" : ObjectId("58db5a628f7b5013ad477566"),
"district" : "Dibrugarh",
"state" : "Assam",
"village" : "Dibrugarh"
},
{
"_id" : ObjectId("58db5a628f7b5013ad47756d"),
"district" : "Lakhimpur",
"state" : "Assam",
"village" : "Kadam"
},
{
"_id" : ObjectId("58db5a628f7b5013ad47756e"),
"district" : "Sonitpur",
"state" : "Assam",
"village" : "Helem"
},
{
"_id" : ObjectId("58db5a628f7b5013ad477572"),
"district" : "Gandhinagar",
"state" : "Gujarat",
"village" : "Mansa"
},
{
"_id" : ObjectId("58db5a628f7b5013ad477573"),
"district" : "Gandhinagar",
"state" : "Gujarat",
"village" : "Kalol"
},
{
"_id" : ObjectId("58db5a628f7b5013ad477574"),
"district" : "Ahmadabad",
"state" : "Gujarat",
"village" : "Barwala"
}

我想按照以下格式按州、地区和村庄对其进行分组

[
{
"state": "Gujarat",
"districts": [
{
"district": "Gandhinagar",
"villages": [
{
"village": "Mansa"
},
{
"village": "Kalol"
}
]
},
{
"district": "Ahmadabad",
"villages": [
{
"village": "Barwala"
}
]
}
]
},
{
"state": "Assam",
"districts": [
{
"district": "Sonitpur",
"villages": [
{
"village": "Helem"
}
]
},
{
"district": "Lakhimpur",
"villages": [
{
"village": "Kadam"
}
]
},
{
"district": "Dibrugarh",
"villages": [
{
"village": "Dibrugarh"
}
]
}
]
},
{
"state": "Andhra Pradesh",
"districts": [
{
"district": "Chittor",
"villages": [
{
"village": "Chittor"
}
]
}
]
}
]

我尝试过但没有找到获得此类聚合的方法。

1) db.historical_prices.aggregate({$group: {_id: {"state": "$state"}}}, {$group: {_id: {"commodity": "$commodity"}}})

2) db.places.aggregate()
.match(qb.where("enabled").eq(false))
.group({ _id: {"state": "$state", "district": "$district"}, "districts": {$push: {district: "$district"}}, })

我在 elasticsearch 中实现了这种聚合。

GET /places/_search
{
"query": { "match_all": {} },
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
},
"aggs": {
"group_by_district": {
"terms": {
"field": "district.keyword"
},
"aggs": {
"group_by_village": {
"terms": {
"field": "village.keyword"
}
}
}
}
}
}
}
}

如何在 MongoDB 中获取它?因为我不想仅仅为了这样做而使用 elasticsearch

最佳答案

您可以尝试以下聚合。以下查询 $group 上的 statedistrict 以累积 villages 后跟 $groupstate 上累积 district 和之前收集的 villages

db.collection.aggregate([{
$group: {
_id: {state:"$state", district:"$district"},
"villages":{$addToSet:{village:"$village"}}
}
},{
$group: {
_id: {state:"$_id.state"},
"districts":{$push:{villages:"$villages", district:"$_id.district"}}
}
}])

关于mongodb - 聚合在 Mongodb 中的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43292367/

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