如何在 mongodb 中对数组进行 AND 查询?

发布于 2024-08-15 11:40:04 字数 85 浏览 3 评论 0原文

我有一个带有标签的数组,它是文档的一部分,例如 [“红色”,“绿色”,“蓝色”,“白色”,“黑色”]

现在我想找到所有具有红色和蓝色的文档。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷乱花海 2024-08-22 11:40:05

另外,如果有人想知道如何否定逐项搜索,即查找匹配“红色”和“蓝色”且不匹配“绿色”和“白色”的记录,这可以通过 $nin 运算符,当有人阅读 $nin 文档时,这可能并不明显 ( http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24nin - 解析描述对我来说很棘手):

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

这非常酷,因为它允许相对较好的带有否定的搜索语法:

tokenRequired1 tokenRequired2 !tokenForbidden1 !tokenForbidden2

非常自然的 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):

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.

深居我梦 2024-08-22 11:40:04

使用 $all 条件查找同时匹配“红色”和“蓝色”条件的记录。

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

如果您想要匹配“红色”或“蓝色”的记录,则可以使用 $in 条件。

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

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"]}})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文