Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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.

Problem courtesy of: ezmilhouse

Solution

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.

model.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
        mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
    ]}
}, function(err, docs){
     console.log(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

Solution courtesy of: Daniel Mendel

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×