这里我有一个示例嵌套数组。我在这个深度嵌套的集合上编写正确的查询时遇到了问题。
{
"productUUID" : "craft001",
"providers": [
{
"providerUUID": "prov001",
"orgs": [
{
"orgUUID": "org001",
"location": {
"buildings": [
{
"buildingUUID": "sit001",
"floors": [
{
"floorUUID": "GrndFlr",
"assets": [ ],
"agents": [ ],
"users": [ ]
},
{
"floorUUID": "1stFlr",
"assets": [ ],
"agents": [ ],
"users": [ ]
}
]
},
{
"buildingUUID": "ist001",
"floors": [ ]
}
]
}
},
{
"orgUUID": "org002",
"location": {
"buildings": [ ]
}
}
]
},
{
"providerUUID": "prov002",
"orgs": [ ]
}
]
}
用简单的词语提问,“1。获取orgUUID
以下的所有providerUUID: "prov001"
”。
同样,“2。将所有floorUUID
设为"buildingUUID": "sit001"
”。
如果有人可以帮我解决第一个问题,我希望自己可以解决第二个问题。
答案 0 :(得分:1)
Mongo aggregation用于查找嵌套文档。首先unwind
所有providers
数组然后使用match
匹配providerUUID
给定prov001
,然后使用project
获取所有orgUUID
和聚合查询为:
db.collectionName.aggregate({"$unwind":"$providers"},
{"$match":{"providers.providerUUID":"prov001"}},
{"$project":{"orgUUID":"$providers.orgs.orgUUID"}},
{"$unwind":"$orgUUID"},
{"$project":{"_id":0,"orgUUID":1}}
).pretty()
这将返回数组中的所有orgUUID
。
如果您使用$elemMacth,则此运营商将其自身限制为
$ elemMatch运算符匹配包含数组字段的文档,其中至少有一个元素符合所有指定的查询条件。
elemMatch
查询为:
db.collectionName.find({"providers":{"$elemMatch":{"providerUUID":"prov001"}}},
{"providers.$.providerUUID.orgs.orgUUID":1}).pretty()
它返回整个匹配的providers
数组。
我希望你能自己找出" 2" 问题查询,如果你在找到" 2" 查询我也会发布" 2" 查询。尝试自己找出第二个查询答案:)
答案 1 :(得分:0)
出于某种原因,我必须更改集合中的数据,如下所示。
{
"productUUID": "prod001",
"providers": [
{
"providerUUID": "prov001",
"orgs": [
{
"orgUUID": "org001",
"floors": [
{ "floorUUID": "SIT_GrndFlr" },
{ "floorUUID": "SIT_1stFlr" }
],
"assets": [{},{}],
"agents": [{},{}],
"users": [{},{}]
},
{
"orgUUID": "org002",
"floors": [
{ "floorUUID": "IST_1stFlr" },
{ "floorUUID": "IST_2ndFlr" }
],
"assets": [{},{}],
"agents": [{},{}],
"users": [{},{}]
}
]
},
{
"providerUUID": "prov002",
"orgs": [
{
"orgUUID": "org001",
"floors": [{},{}],
"assets": [{},{}],
"agents": [{},{}],
"users": [{},{}]
},
{
"orgUUID": "org002",
"floors": [{},{}],
"assets": [{},{}],
"agents": [{},{}],
"users": [{},{}]
}
]
}
]
}
所以,现在在@yogesh的帮助下,我被介绍到aggregate
并且能够为我的问题编写查询。
1. Get all `orgUUID`s under `providerUUID: "prov001"`.
db.collectionName.aggregate({"$unwind":"$providers"},
{"$match":{"providers.providerUUID":"prov001"}},
{"$project":{"orgUUID":"$providers.orgs.orgUUID"}},
{"$unwind":"$orgUUID"},
{"$project":{"_id":0,"orgUUID":1}}
)
2. Get all `floorUUID`s under `orgUUID : "org001"`.
db.collectionName.aggregate(
{ "$unwind" : "$providers" },
{ "$match" : { "providers.providerUUID" : "prov001" } },
{ "$unwind" : "$providers.orgs" },
{ "$match" : { "providers.orgs.orgUUID" : "org001" } },
{ "$project" : { "floorUUID" : "$providers.orgs.floors.floorUUID" } },
{ "$unwind" : "$floorUUID" },
{ "$project" : { "_id":0 , "floorUUID" : 1 } }
)