Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I have an array of _ids and I want to get all docs accordingly, what's the best way to do it?

Something like ...

// doesn't work ... of course ...
model.find({ 

'_id' : [ '4ed3ede8844f0f351100000c', 

'4ed3f117a844e0471100000d', 

'4ed3f18132f50c491100000e' 

}, function(err, docs){ 

console.log(docs); 

});

The array might contain hundreds of _ids.

1 Answer

0 votes
by (106k points)

To find all documents with IDs listed in array the find function in mongoose is a full query to MongoDB. This means you can use the handy MongoDB $in a clause, which works just like the SQL version of the same.

model.find({ 

'_id': { $in: [ 

mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),

mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 

mongoose.Types.ObjectId('4ed3f18132f50c491100000e') 

]} 

}, function(err, docs){ 

console.log(docs);

});

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...