- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retrieving specific documents from collection by _id in MongoDB
To retrieve document from collection by _id, use find() with $in. Let us create a collection with documents −
> db.demo281.insertOne({"Name":"Chris","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e4aac28dd099650a5401a66") } > db.demo281.insertOne({"Name":"Bob","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5e4aac46dd099650a5401a67") } > db.demo281.insertOne({"Name":"David","Age":28}); { "acknowledged" : true, "insertedId" : ObjectId("5e4aac4fdd099650a5401a68") }
Display all documents from a collection with the help of find() method −
> db.demo281.find();
This will produce the following output −
{ "_id" : ObjectId("5e4aac28dd099650a5401a66"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e4aac46dd099650a5401a67"), "Name" : "Bob", "Age" : 23 } { "_id" : ObjectId("5e4aac4fdd099650a5401a68"), "Name" : "David", "Age" : 28 }
Following is the query to retrieve specific documents from collection by _id −
>db.demo281.find({_id:{$in:[ObjectId("5e4aac28dd099650a5401a66"),ObjectId("5e4aac46dd099650a5401a67")]}});
This will produce the following output −
{ "_id" : ObjectId("5e4aac28dd099650a5401a66"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e4aac46dd099650a5401a67"), "Name" : "Bob", "Age" : 23 }
Advertisements