- Trending Categories
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 a record by _id in MongoDB?
In order to find record by _id in MongoDB, you can use the following syntax
db.yourCollectionName.find({"_id":yourObjectId});
Let us create a collection with documents
> db.findRecordByIdDemo.insertOne({"CustomerName":"Larry","CustomerAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c9dc2c875e2eeda1d5c3671") } > db.findRecordByIdDemo.insertOne({"CustomerName":"Bob","CustomerAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5c9dc2d175e2eeda1d5c3672") } > db.findRecordByIdDemo.insertOne({"CustomerName":"Carol","CustomerAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c9dc2d775e2eeda1d5c3673") } > db.findRecordByIdDemo.insertOne({"CustomerName":"David","CustomerAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c9dc2e375e2eeda1d5c3674") }
Following is the query to display all documents from a collection with the help of find() method
> db.findRecordByIdDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9dc2c875e2eeda1d5c3671"), "CustomerName" : "Larry", "CustomerAge" : 26 } { "_id" : ObjectId("5c9dc2d175e2eeda1d5c3672"), "CustomerName" : "Bob", "CustomerAge" : 20 } { "_id" : ObjectId("5c9dc2d775e2eeda1d5c3673"), "CustomerName" : "Carol", "CustomerAge" : 22 } { "_id" : ObjectId("5c9dc2e375e2eeda1d5c3674"), "CustomerName" : "David", "CustomerAge" : 24 } Following is the query to find record by _id in MongoDB: > db.findRecordByIdDemo.find({"_id":ObjectId("5c9dc2d175e2eeda1d5c3672")}).pretty();
This will produce the following output
{ "_id" : ObjectId("5c9dc2d175e2eeda1d5c3672"), "CustomerName" : "Bob", "CustomerAge" : 20 }
Advertisements