【发布时间】:2014-01-28 21:53:22
【问题描述】:
我有一个 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 数据库仍然很陌生,并且不确定我需要在这里使用的最佳范例。非常感谢任何帮助。
【问题讨论】: