Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The array might contain hundreds of _ids.

like image 662
ezmilhouse Avatar asked Nov 28 '11 23:11

ezmilhouse


People also ask

How do I search multiple documents in MongoDB?

You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.

What does find by id return Mongoose?

findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

What is $Push in Mongoose?

The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

What is the difference between schema and model in Mongoose?

A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.


2 Answers

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

like image 157
Daniel Mendel Avatar answered Oct 02 '22 11:10

Daniel Mendel


Ids is the array of object ids:

const ids =  [     '4ed3ede8844f0f351100000c',     '4ed3f117a844e0471100000d',      '4ed3f18132f50c491100000e', ]; 

Using Mongoose with callback:

Model.find().where('_id').in(ids).exec((err, records) => {}); 

Using Mongoose with async function:

const records = await Model.find().where('_id').in(ids).exec(); 

Or more concise:

const records = await Model.find({ '_id': { $in: ids } }); 

Don't forget to change Model with your actual model.

like image 40
snnsnn Avatar answered Oct 02 '22 11:10

snnsnn