我有一个以下架构的文档。我想根据键building
和rooms
查找文档。这些键嵌套在列表中,该列表嵌套在列表中。我在下面的架构中提到了列表rooms(OR)
,列表Department1(AND)
和列表Departments(OR)
之间想要的关系。
{
"Departments" : [
{
"Department" : [
{
"building" : "alps",
"rooms" : [
"1","2" ------ OR relationship ------
]
}, ------ AND relationship ------
{
"building" : "sierra",
"rooms" : [
"1"
]
}
]
}, ------ OR relationship ------
{
"Department" : [
{
"building" : "sierra",
"rooms" : [
"1"
]
}
]
}
]
}
在这种情况下,我被困在下面的filter_query中-
db.getCollection('department_buildings').find({"$and":[{"Departments.Department.building":"alps","Departments.Department.rooms": {"$in":["1","2"]}}, {"Departments.Department.building":"sierra","Departments.Department.rooms": {"$in":["1"]}}]})
此查询不适用于Department
(AND)
关系,因为它在Departments
上查找房间/建筑物,而我们想查找此AND
关系在Department
中。因此,此查询将返回上面的文档,但同时也会返回下面的文档,这不是预期的结果。
{
"Departments" : [
{
"Department" : [
{
"building" : "alps",
"rooms" : [
"1","2"
]
}
]
},
{
"Department" : [
{
"building" : "sierra",
"rooms" : [
"1"
]
}
]
}
]
}
我是MongoDB的新手,不确定如何实现。
答案 0 :(得分:0)
除了我之前使用的$elemMatch
之外,我还可以使用@all
和$and
来实现这一目标。以下是对我有用的查询。
db.getCollection('catalog_personalization_policies').find({
"$and": [
{
"Departments": {
"$elemMatch": {
"Department": {
"$all": [
{
"$elemMatch": {
"rooms": {
"$in": [
"1"
]
},
"building": "alps"
}
},
{
"$elemMatch": {
"rooms": {
"$in": [
"1"
]
},
"building": "sierra"
}
}
]
}
}
}
}
]
})