java - 如何根据一些特定的标准检索深度嵌套的数组spring mongodb
问题描述
我有一个名为 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、定价和合同详细信息。例如,如果我搜索 billCode code5,那么数据库的相应输出应该是:
{
"customerId":"Id",
"contract":[
{
"contractId":"con2",
"contractName":"conName2",
"pricing":[
{
"pricingName":"priceName3",
"billProfile":[
{
"billCode":"code5",
"billName":"Name5"
}
]
}
]
}
]
}
到目前为止我已经尝试过:
使用位置运算符 $ 但它只能用于深入文档的一层。尝试检索具有 billCode 但错误定价和 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 ] }
]
}
}
}
}
}
]
)
推荐阅读
- vmware-fusion - 在 VM Ware 上运行 Parrot OS 安装程序时出现问题
- multithreading - 如何在等待用户输入时使用 Discord bot 打印消息
- c# - 实体类型
不是当前上下文模型的一部分 - python - 在python中将所有表格从word转移到excel
- python - Python返回一个按相同键对值进行分组的字典
- javascript - 在功能组件内调用 useStore 但出现错误
- python - 每当我使用命令时,它都会显示“找不到命令”或根本不说任何内容
- c# - Linq 返回 Nullable 对象必须有一个值,因为有些列是 null
- r - 对于相同大小的两个数据帧 df 和 logicaldf,命令 df[logicaldf, ] 在 R 中执行什么?
- c# - 身份服务器 4 会话/cookie 问题