How do you do an AND query on an array in mongodb?

核能气质少年 提交于 2020-01-03 17:02:03

问题


I have an array with tags which is part of a document, eg ["red", "green", "blue", "white", "black"]

Now I want to find all documents, which have red AND blue.


回答1:


Use the $all condition to find records that match both "red" and "blue" conditions.

db.my_collection.find({tags: { $all : ["red","blue"]}})

If you want records that match either "red" or "blue" then you can use the $in condition.

db.my_collection.find({tags: { $in : ["red","blue"]}})



回答2:


Also in case someone is wondering how to negate itemized search, i.e. find record that match both "red" and "blue" and DO NOT match "green" and "white" this can be accomplished with the $nin operator, which may not be obvious when someone is reading $nin docs (http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24nin - parsing description was tricky for me):

db.my_collection.find({tags: { $all : ["red","blue"], $nin : ["green", "white" ]}})

This is very cool, as it allows relatively nice search syntax with negation:

tokenRequired1 tokenRequired2 !tokenForbidden1 !tokenForbidden2

Very natural, Gmail-style search.

As suggested here and here you could do full text search if you create an array of all tokens from a record, though I have no idea if it's efficient or even the best way to do it.



来源:https://stackoverflow.com/questions/1937183/how-do-you-do-an-and-query-on-an-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!