Can I retrieve multiple documents from MongoDB by id?


Yes, to retrieve multiple docs from MongoDB by id, use the $in operator. The syntax is as follows

db.yourCollectionName.find({_id:{$in:[yourValue1,yourValue2,yourValue3,...N]}});

Let us first create a collection with documents:

> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":10,"CustomerName":"John"});
{ "acknowledged" : true, "insertedId" : 10 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":14,"CustomerName":"Chris"});
{ "acknowledged" : true, "insertedId" : 14 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":20,"CustomerName":"Robert"});
{ "acknowledged" : true, "insertedId" : 20 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":25,"CustomerName":"Sam"});
{ "acknowledged" : true, "insertedId" : 25 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":30,"CustomerName":"Bob"});
{ "acknowledged" : true, "insertedId" : 30 }
> db.retrieveMultipleDocsByIdDemo.insertOne({"_id":34,"CustomerName":"Carol"});
{ "acknowledged" : true, "insertedId" : 34 }

Following is the query to display all documents from a collection with the help of find() method

> db.retrieveMultipleDocsByIdDemo.find().pretty();

This will produce the following output

{ "_id" : 10, "CustomerName" : "John" }
{ "_id" : 14, "CustomerName" : "Chris" }
{ "_id" : 20, "CustomerName" : "Robert" }
{ "_id" : 25, "CustomerName" : "Sam" }
{ "_id" : 30, "CustomerName" : "Bob" }
{ "_id" : 34, "CustomerName" : "Carol" }

Following is the query to retrieve multiple documents from MongoDB by id

> db.retrieveMultipleDocsByIdDemo.find({_id:{$in:[10,20,30]}});

This will produce the following output

{ "_id" : 10, "CustomerName" : "John" }
{ "_id" : 20, "CustomerName" : "Robert" }
{ "_id" : 30, "CustomerName" : "Bob" }

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements