简体   繁体   中英

How to retrive documents by multiple fields using $in operator

I have a collection

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" });

I have an array of pairs

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

Currently I am doing

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" } ]

Is it possible to retrive documents by multiple fields using $in operator with only 1 query?

If I wanted to retrive only by one field, I would do

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

$in should work equally well for objects as it does for primitive values, but anyway if you're looking for a top-level object that matches one of the parameter combinations, you don't even need $in ; $or should do the trick.

Basically, all you have to do is convert ary into an array of objects instead of arrays, and then you should be able to use these objects as the possible filters passed to $or .

Assuming you have a toObject function that receives an array of length 2 and returns an object with "first" and "second" properties, the code might look something like this:

var ary = [ [ "apple", "tree" ], [ "space" , "moon" ], [ "medal", "sport" ] ];
var object_ary = ary.map(toObject);
db.list.find({ $or: object_ary });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM