- 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
Use ObjectId under findOne() to fetch a specific record in MongoDB?
Let us first create a collection with documents −
> db.findOneWorkingDemo.insertOne({"ClientId":1,"ClientName":"Larry","ClientAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c1716d78f205348bc64d") } > db.findOneWorkingDemo.insertOne({"ClientId":2,"ClientName":"Chris","ClientAge":28}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c17d6d78f205348bc64e") } > db.findOneWorkingDemo.insertOne({"ClientId":3,"ClientName":"Robert","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c1896d78f205348bc64f") }
Following is the query to display all documents from a collection with the help of find() method −
> db.findOneWorkingDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd7c1716d78f205348bc64d"), "ClientId" : 1, "ClientName" : "Larry", "ClientAge" : 26 } { "_id" : ObjectId("5cd7c17d6d78f205348bc64e"), "ClientId" : 2, "ClientName" : "Chris", "ClientAge" : 28 } { "_id" : ObjectId("5cd7c1896d78f205348bc64f"), "ClientId" : 3, "ClientName" : "Robert", "ClientAge" : 34 }
Following is the query to implement findOne() with ObjectId −
> db.findOneWorkingDemo.findOne({"_id":ObjectId("5cd7c17d6d78f205348bc64e")});
This will produce the following output −
{ "_id" : ObjectId("5cd7c17d6d78f205348bc64e"), "ClientId" : 2, "ClientName" : "Chris", "ClientAge" : 28 }
Advertisements