简体   繁体   English

如何使用MongoDB $ elemMatch获得所有匹配项?

[英]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. 当您要使用多个运算符条件(例如$ gt或$ lt),但只希望其中一个数组项与所有条件匹配的那些文档时,它是必需的。 Without the $elemMatch operator, you get results where each condition is met by at least one array entry, but not necessarily all by the same entry. 没有$ elemMatch运算符,您将获得结果,其中至少一个数组条目满足每个条件,但同一条目不一定都满足。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM