gpt4 book ai didi

java - 如何根据某些特定条件检索深度嵌套数组 spring mongodb

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

我有一个名为 abc 的集合(假设),在这个集合中我有多个文档,其结构如下:

{
"customerId":"Id",
"contract":[
{
"contractId":"con1",
"contractName":"conName1",
"pricing":[
{
"pricingName":"priceName1",
"billProfile":[
{
"billCode":"code1",
"billName":"Name1"
},
{
"billCode":"code2",
"billName":"Name2"
}
]
},
{
"pricingName":"priceName2",
"billProfile":[
{
"billCode":"code3",
"billName":"Name3"
}
]
}
]
},
{
"contractId":"con2",
"contractName":"conName2",
"pricing":[
{
"pricingName":"priceName3",
"billProfile":[
{
"billCode":"code4",
"billName":"Name4"
},
{
"billCode":"code5",
"billName":"Name5"
}
]
},
{
"pricingName":"priceName4",
"billProfile":[
{
"billCode":"code6",
"billName":"Name6"
}
]
}
]
}
]
}

对于像这样的多个文档,我想搜索一个特定的账单代码,然后返回该账单代码的相应 billProfile、定价和契约(Contract)详细信息。例如,如果我搜索 billCode code5,那么数据库的相应输出应该是:

{
"customerId":"Id",
"contract":[
{
"contractId":"con2",
"contractName":"conName2",
"pricing":[
{
"pricingName":"priceName3",
"billProfile":[
{
"billCode":"code5",
"billName":"Name5"
}
]
}
]
}
]
}

到目前为止我尝试了什么:

使用位置运算符 $ 但它只能用于深入文档的一层。尝试检索具有 billCode 的特定契约(Contract),但错误的定价和 billprofile 也包含在结果集中。

我知道我们可以对这件事使用聚合,但我不知道如何对这种复杂的检索执行聚合。我需要在我的 java spring 项目中使用聚合来从数据库中获取数据,然后将其存储在我的类模型中。知道如何对该数据集执行聚合吗?

最佳答案

您可以使用 $filter$map 实现相同的目的。

注意:我没有在 Java 中测试过。但它在 MongoDB GUI

中工作
db.getCollection('customer').aggregate([ 
{ "$project": {
"_id":1,
"customerId" :1,
"contract": {
"$filter": {
"input": {
"$map": {
"input": "$contract",
"as": "con",
"in": {
"pricing": {
"$filter": {
"input": {
"$map": {
"input": "$$con.pricing",
"as": "pric",
"in" : {
"billProfile" : {
"$filter" : {
"input" : "$$pric.billProfile",
"as" : "billProf",
"cond": {
"$eq": [ "$$billProf.billCode", "code5" ]
}

}
}
}
}
},
"as": "pric",
"cond": {
"$and": [
{ "$gt": [ { "$size": "$$pric.billProfile" }, 0 ] }
]
}
}
}
}
}
},
"as": "con",
"cond": {
"$and": [
{ "$gt": [ { "$size": "$$con.pricing" }, 0 ] }
]
}
}
}
}
}
]
)

关于java - 如何根据某些特定条件检索深度嵌套数组 spring mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52612744/

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