MongoDB:$ elemMatch和$ and和在数组内查找对象之间有什么区别? [英] MongoDB: what is the difference between $elemMatch and $and to find objects inside array?
问题描述
查询运算符$and
db.collection.find({$and: [{"array.field1": "someValue"}, {"array.field2": 3}]})
和投影运算符$elemMatch
db.collection.find({array: {$elemMatch: {field1: "someValue", field2: 3}}})
查找包含数组中的对象字段的文档?
to find documents which contain the object fields inside an array?
推荐答案
您的第一个查询将找到文档,其中数组具有至少一个具有field1 = somevalue的元素和至少一个具有field2 = 3的元素.这两个元素可以不同. 第二个将检索文档,其中数组具有至少一个同时匹配两个条件的元素. 这是一个数据样本来说明:
Your first query will find documents, where array have at least one element with field1= somevalue and at least one element with field2=3. Both elements can be different. The second one will retrieve documents where array have at least one element matching the two conditions simultaneously. Here's a data sample to explain :
{
array: [
{
field1: 1,
},
{
field2: 2
},
{
field1: 1,
field2: 3
},
]
},
{
array: [
{
field1: 1,
field2: 2
},
{
field2: 3
}
]
},
{
array: [
{
field1: 1,
field2: "other"
},
{
field2: 2
}
]
}
第一个查询
db.collection.find({"array.field1":1,"array.field2":2})(等效 到您的$ and语法)
db.collection.find({"array.field1": 1,"array.field2": 2}) (equivalent to your $and syntax)
将返回三个文档,
db.collection.find({array:{$ elemMatch:{field1:1,field2:2}}})
db.collection.find({array: {$elemMatch: {field1: 1, field2: 2}}})
将仅返回第二个文档(唯一一个具有与两个条件都匹配的元素的文档)
will return only the second document (the only one having an element matching both criterias)
第一个查询的逻辑运算符是OR,第二个查询的逻辑运算符是AND,在数组元素级别.
EDIT : The logical operator of the first query is OR, for the second one it's AND, at level of array element.
这篇关于MongoDB:$ elemMatch和$ and和在数组内查找对象之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!