我有一个 MongoDB 集合,其中特定的字符串可能出现在多个字段中的任何一个中:
{"_id":1, "field1": "foo", "field2": "bar", "field3": "baz", "otherfield": "stuff"},
{"_id":2, "field1": "bar", "field2": "baz", "field3": "foo", "otherfield": "morestuff"},
{"_id":3, "field1": "baz", "field2": "foo", "field3": "bar", "otherfield": "you get the idea"}
我需要查询,以便返回所有记录,其中一组字段中的任何一个等于数组中的任何值......基本上,如果我有 ["foo","bar"]
如果这些字符串中的任何一个在 field1 或 field2(但不是任何其他字段)中,我需要它来匹配。
显然我可以通过一系列的多个查询来做到这一点
db.collection.find({"field1":{"$in":["foo","bar"]}})
db.collection.find({"field2":{"$in":["foo","bar"]}})
等等,我还做了一个非常大的 $or 查询,将它们连接在一起,但它似乎效率太低(我的实际集合需要匹配可能出现在 9 个字段中的任何一个中的 15 个字符串中的任何一个) ...但我对 nosql 数据库仍然很陌生,并且不确定我需要在这里使用的最佳范例。非常感谢任何帮助。
最佳答案
试试
db.collection.find(
// Find documents matching any of these values
{$or:[
{"field1":{"$in":["foo","bar"]}},
{"field2":{"$in":["foo","bar"]}}
]}
)
另请参阅 question
关于arrays - 在 MongoDB 中搜索多个字段的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21417711/