Arrays MongoDB$和仅当$和在文档的同一数组索引中为true时才进行查询-特别是对于双嵌套数组
1。仅当$and出现在同一数组元素中时才查找匹配项 假设mongoDB中有这两个文档:Arrays MongoDB$和仅当$和在文档的同一数组索引中为true时才进行查询-特别是对于双嵌套数组,arrays,mongodb,mongodb-query,aggregation-framework,pymongo,Arrays,Mongodb,Mongodb Query,Aggregation Framework,Pymongo,1。仅当$and出现在同一数组元素中时才查找匹配项 假设mongoDB中有这两个文档: {_id: 1, people: [{height: 10, age: 10}, {height: 5, age: 5}]} {_id: 2, people: [{height: 10, age: 5}, {height: 5, age: 10}]} {_id: 1, families: [people: [{height: 10, age: 10}, {height: 5, age: 5}], peop
{_id: 1, people: [{height: 10, age: 10}, {height: 5, age: 5}]}
{_id: 2, people: [{height: 10, age: 5}, {height: 5, age: 10}]}
{_id: 1, families: [people: [{height: 10, age: 10}, {height: 5, age: 5}], people: [{height: 0, age: 0}, {height: 0, age: 0}]]}
{_id: 2, families: [people: [{height: 10, age: 5}, {height: 0, age: 0}], people: [{height: 5, age: 10}, {height: 0, age: 0}]]}
我们要匹配每个文档,其中至少有一个人的身高
和年龄
都>=10。
我当前的查询类似于
{$and:[{people.height:{$gte,10}},{people.age:{$gte:10}]}
但是,当只有ID 1包含一个大于等于10的人时,这将返回ID 1和ID 2
2。与上述问题相同,但该列表嵌套在第二个列表中。如果至少有一个人的年龄>=10且身高>/code>小于或等于10则只应返回ID
假设mongoDB中有这两个文档:
{_id: 1, people: [{height: 10, age: 10}, {height: 5, age: 5}]}
{_id: 2, people: [{height: 10, age: 5}, {height: 5, age: 10}]}
{_id: 1, families: [people: [{height: 10, age: 10}, {height: 5, age: 5}], people: [{height: 0, age: 0}, {height: 0, age: 0}]]}
{_id: 2, families: [people: [{height: 10, age: 5}, {height: 0, age: 0}], people: [{height: 5, age: 10}, {height: 0, age: 0}]]}
如何构造只匹配id 1的查询
3。为此类查询建立正确的索引
目前我有一个相当于{families.people.height,families.people.age}
的复合索引,但我相信这不会针对我应该使用的查询进行优化。索引是否应该改为{families.people}
注意:假设此查询在mongoDB上运行,包含约70000000个文档因此,您没有澄清数据输出格式的要求。假设从聚合返回的数据架构不需要与集合中的文档相同,则可以使用$unwind
示例:
db.coll.aggregate([
{ $unwind: "$people" },
{ $addFields: {
isHeightMatch: { $gte: [ "$people.height", 10 ] },
isAgeMatch: { $gte: [ "$people.age", 10 ] }
}
},
{ $match: {
$and: [
{ isHeightMatch: true },
{ isAgeMatch: true }
]
}
},
{ $project: {
"isHeightMatch": 0,
"isAgeMatch": 0
}
}
])
{ "_id" : 1, "people" : { "height" : 10, "age" : 10 } }
输出:
db.coll.aggregate([
{ $unwind: "$people" },
{ $addFields: {
isHeightMatch: { $gte: [ "$people.height", 10 ] },
isAgeMatch: { $gte: [ "$people.age", 10 ] }
}
},
{ $match: {
$and: [
{ isHeightMatch: true },
{ isAgeMatch: true }
]
}
},
{ $project: {
"isHeightMatch": 0,
"isAgeMatch": 0
}
}
])
{ "_id" : 1, "people" : { "height" : 10, "age" : 10 } }
您可以使用来实现更具体的数组元素匹配
为了获得至少一个身高和年龄均大于等于10的人,您可以使用以下查询:
{ people: { $elemMatch: { $and: [ {height: {$gte: 10} }, { age: {$gte: 10} } ] } } }
{ 'families.people': { $elemMatch: { $and: [ {height: {$gte: 10} }, { age: {$gte: 10} } ] } } }
这同样适用于嵌套数组。如果人员数组嵌套在族数组中,则可以使用以下查询:
{ people: { $elemMatch: { $and: [ {height: {$gte: 10} }, { age: {$gte: 10} } ] } } }
{ 'families.people': { $elemMatch: { $and: [ {height: {$gte: 10} }, { age: {$gte: 10} } ] } } }
我希望这会有所帮助。案例2中的文档不是有效文档。对于第一种情况
{$elemMatch:{height:{$gte:10},age:{$gte:10}}}
在