

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }
- Related Questions & Answers
- How to retrieve documents from a collection in MongoDB?
- How can I aggregate nested documents in MongoDB?
- MongoDB filter multiple sub-documents?
- How to retrieve all the documents from a MongoDB collection using Java?
- MongoDB, finding all documents where property id equals to record id?
- Search for multiple documents in MongoDB?
- MongoDB query to add multiple documents
- Fetch specific multiple documents in MongoDB
- Retrieving specific documents from collection by _id in MongoDB
- Retrieve user id from array of object - JavaScript
- How to update multiple documents in MongoDB?
- How to merge multiple documents in MongoDB?
- Matching MongoDB collection items by id?
- How can I rename a field for all documents in MongoDB?
- How to retrieve a value from MongoDB by its key name?
Advertisements