- 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
How to find by id in MongoDB?
To find by id in MongoDB, use the find() method as in the below syntax −
db.findByIdDemo.find({"_id" :yourObjectId});
To understand the above syntax, let us create a collection with documents −
> db.findByIdDemo.insertOne({"Value":10}); { "acknowledged" : true, "insertedId" : ObjectId("5e07158925ddae1f53b621fc") } > db.findByIdDemo.insertOne({"Value":500}); { "acknowledged" : true, "insertedId" : ObjectId("5e07158c25ddae1f53b621fd") } > db.findByIdDemo.insertOne({"Value":1000}); { "acknowledged" : true, "insertedId" : ObjectId("5e07159125ddae1f53b621fe") }
Following is the query to display all documents from a collection with the help of find() method −
> db.findByIdDemo.find();
This will produce the following output −
"_id" : ObjectId("5e07158925ddae1f53b621fc"), "Value" : 10 } { "_id" : ObjectId("5e07158c25ddae1f53b621fd"), "Value" : 500 } { "_id" : ObjectId("5e07159125ddae1f53b621fe"), "Value" : 1000 }
Following is the query to find by id in MongoDB −/p>
> db.findByIdDemo.find({"_id" :ObjectId("5e07158c25ddae1f53b621fd")});
This will produce the following output −
{ "_id" : ObjectId("5e07158c25ddae1f53b621fd"), "Value" : 500 }
Advertisements