gpt4 book ai didi

java - Spring mongodb查询包含嵌套数组的嵌套数组

转载 作者:行者123 更新时间:2023-12-01 19:30:27 25 4
gpt4 key购买 nike

我有这3类

@Document(collection = "Countries")
class CountryDoc
{
@Id
lateinit var id : String

var name : String = ""

var governorates : ArrayList<Governorate> = ArrayList()

}

class Governorate
{
var id : String = ""

var name : String = ""

var cardinalPoint : CardinalPoint = CardinalPoint.SOUTH_WEST

var cities : ArrayList<City> = ArrayList()
}

class City
{
var id : String = ""

var name : String = ""
}

我想获取一个城市的完整地址,结果一定是这样的

{
"countryId" : ""
"countryName" : "",
"governorateId" : "",
"governorateName" : "",
"cardinalPoint" : ""
"cityId" : "",
"cityName" : ""
}

我尝试了这个查询,但它不起作用,我只有国家/地区的信息

    val countryCriteria = Criteria.where("id").`is`(countryId)
val governorateCriteria = Criteria.where("id").`is`(governorateId)
val cityCriteria = Criteria.where("id").`is`(cityId)

val aggregation = Aggregation.newAggregation(
Aggregation.match(countryCriteria),
Aggregation.project().and("id").`as`("countryId").and("name").`as`("countryName"),
Aggregation.unwind("governorates"),
Aggregation.match(governorateCriteria),
Aggregation.project().and("name").`as`("governorateName").and("id").`as`("governorateId").and("cardinalPoint").`as`("cardinalPoint")
Aggregation.unwind("cities"),
Aggregation.match(cityCriteria)
Aggregation.project().and("name").`as`("cityName").and("id").`as`("cityId")
)

val result = mongoDb.aggregate(aggregation, CountryDoc::class.java, Address::class.java).uniqueMappedResult

我不明白为什么这对我不起作用,有人可以帮助我吗?

最佳答案

您可以从我在 Mongoshell 上编写的这个查询中获得启发:

可以在 Mongo playground 上测试查询

db.city.aggregate([
{
"$match": {
"_id": "c1"
}
},
{
"$lookup": {
"from": "governate",
"as": "governates",
"localField": "_id",
"foreignField": "cities"
}
},
{
"$project": {
"governate": {
$arrayElemAt: [
"$governates",
0
]
},
"cityName": "$name"
}
},
{
"$lookup": {
"from": "country",
"as": "coutries",
"localField": "governate._id",
"foreignField": "governates"
}
},
{
"$project": {
"country": {
$arrayElemAt: [
"$coutries",
0
]
},
"cityName": 1,
"governateName": "$governate.name",
"governateId": "$governate._id"
}
},
{
"$project": {
"_id": 0,
"cityId": "$_id",
"countryName": "$country.name",
"countryId": "$country._id",
"cityName": 1,
"governateId": 1,
"governateName": 1
}
}
])

我使用的数据如下所示:

db={
"country": [
{
"_id": "1",
"name": "country",
"governates": [
"g1"
]
}
],
"governate": [
{
"_id": "g1",
"name": "governate",
"cities": [
"c1"
]
}
],
"city": [
{
"_id": "c1",
"name": "city"
}
]
}

关于java - Spring mongodb查询包含嵌套数组的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59264215/

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