ezmilhouse ezmilhouse - 1 year ago 598
Node.js Question

mongodb/mongoose findMany - find all documents with IDs listed in array

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 ...

'_id' : [
}, function(err, docs){

The array might contain hundreds of _ids.

Answer Source

The find function in mongoose is a full query to mongoDB. This means you can use the handy mongoDB $in clause, which works just like the SQL version of the same.

    '_id': { $in: [
}, function(err, docs){

This method will work well even for arrays containing tens of thousands of ids. (See Efficiently determine the owner of a record)

I would recommend that anybody working with mongoDB read through the Advanced Queries section of the excellent Official mongoDB Docs

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download