如何使用$ in运算符通过多个字段检索文档

时间:2014-11-26 01:53:50

标签: mongodb

我有一个集合

db.list.insert({ first: "apple", second: "banana" });
db.list.insert({ first: "apple", second: "tree" });
db.list.insert({ first: "space", second: "moon" });
db.list.insert({ first: "medal", second: "sport" });

我有一对数组

ary = [ [ "apple", "tree" ], [ "space" , "moon" ], [ "medal", "sport" ] ]

目前我在做

result_list = []
for a, b in ary
    result_list.push db.list.find({ first: a, second: b })
result_list # => [ { first: "apple", second: "tree" }, { first: "apple", second: "tree" }, { first: "apple", second: "tree" } ]

是否可以使用$ in运算符仅使用1个查询按多个字段检索文档?

如果我只想通过一个字段进行检索,我会做

db.list.find({ "first": { "$in": ary_of_some_words } })

1 个答案:

答案 0 :(得分:1)

$in对于对象应该和原始值一样好用,但无论如何,如果你正在寻找一个匹配其中一个参数组合的顶级对象,你甚至不需要{{ 1}}; $in应该做到这一点。

基本上,您所要做的就是将$or转换为对象数组而不是数组,然后您应该能够将这些对象用作传递给ary的可能过滤器。

假设你有一个$or函数接收一个长度为2的数组并返回一个具有“first”和“second”属性的对象,代码可能如下所示:

toObject