如何在 mongodb 中对数组进行 AND 查询?
我有一个带有标签的数组,它是文档的一部分,例如 [“红色”,“绿色”,“蓝色”,“白色”,“黑色”]
现在我想找到所有具有红色和蓝色的文档。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另外,如果有人想知道如何否定逐项搜索,即查找匹配“红色”和“蓝色”且不匹配“绿色”和“白色”的记录,这可以通过 $nin 运算符,当有人阅读 $nin 文档时,这可能并不明显 ( http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24nin - 解析描述对我来说很棘手):
这非常酷,因为它允许相对较好的带有否定的搜索语法:
非常自然的 Gmail 风格的搜索。
正如建议的这里和这里如果你创建一个包含所有内容的数组,你可以进行全文搜索记录中的令牌,尽管我不知道它是否有效,甚至不知道这是最好的方法。
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):
This is very cool, as it allows relatively nice search syntax with negation:
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.
使用 $all 条件查找同时匹配“红色”和“蓝色”条件的记录。
如果您想要匹配“红色”或“蓝色”的记录,则可以使用 $in 条件。
Use the $all condition to find records that match both "red" and "blue" conditions.
If you want records that match either "red" or "blue" then you can use the $in condition.