我正在尝试使用聚合框架展平嵌套数组,但我无法得到结果。 我的 Collection 是:
[
{
"id" : "xxx",
"countryName" : "xxx",
"cities" : [
{
"id" : "xxx",
"cityName" : "xxx"
},
{
"id" : "xxx",
"cityName" : "xxx"
}
]
}
]
我想获取所有国家的城市,我正在寻找的结果是:
[
{
"id" : "xxx",
"cityName" : "xxx"
},
{
"id" : "xxx",
"cityName" : "xxx"
}
]
我尝试了这个请求:
val aggregation = Aggregation.newAggregation(
Aggregation.group("cities")
)
return mongoDb.aggregate(aggregation, Country::class.java, Any::class.java).mappedResults
但是,我得到了这个结果:
[
{
"_id": [
{
"id": "xxx",
"cityName": "xxx"
},
{
"id": "xxx",
"cityName": "xxx"
}
]
}
]
有人可以帮我吗?
最佳答案
此聚合将帮助您实现结果,但您必须使用 Java
驱动程序对其进行调整:
db.countries.aggregate([
{
"$unwind": "$cities"
},
{
"$project": {
"_id": 0,
"cities": 1
}
},
{
"$replaceRoot": {
"newRoot": "$cities"
}
}
])
关于java - 在 Spring 中使用 mongodb 聚合展平嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59499670/