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.
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.
findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With