[英]How to get all matches with MongoDB $elemMatch?
I have two objects: 我有两个对象:
{
genre: ['music', 'movie']
}
and 和
{
genre: ['movie', 'music']
}
and my query is: 我的查询是:
db.test.find({genre :{ $elemMatch:{ $in : ['movie']}}})
and it only gives me the second object. 而这只给了我第二个目的。 Why?
为什么? I want to get all the docs that contain a specific genre in their arrays no matter where in the array.
我想获取所有在数组中包含特定类型的文档,而不管其在数组中的何处。 How can I do this?
我怎样才能做到这一点?
You need neither $elemMatch
nor $in
in this case. 在这种情况下,您既不需要
$elemMatch
也不需要$in
。 A simple field:value
will match documents where field
is an array and any one of the values in that array is value
. 一个简单的
field:value
将匹配文档,其中field
是一个数组,而该数组中的任何一个值都是value
。 That means 那意味着
db.test.find({genre :'movie'});
will suffice. 就足够了。
The array query operators are required in more complex situations. 在更复杂的情况下,需要数组查询运算符。
$in
is needed when you have a list of possible values and want documents where any of them is found (so db.test.find({genre : { $in:['movie']} });
would work, but would be needlessly convoluted) $in
(因此db.test.find({genre : { $in:['movie']} });
可以,但是可以被不必要的困扰) $all
works like $in but requires that all provided elements are in the array $all
作用类似于$ in,但要求所有提供的元素都在数组中 $elemMatch
is a bit more complex. $elemMatch
有点复杂。 It is required when you want to use multiple operator-conditions (like $gt or $lt) but want only those documents where one array entry matches all the conditions. Remember db.test.find() in general returns you cursor object. 请记住,通常db.test.find()返回您的游标对象。 You can access all doc as follows:
您可以按以下方式访问所有文档:
entry = db.test.find({genre :{ $elemMatch:{ $in : ['movie']}}})
for doc in entry:
print(doc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.