

- 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
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 }
- Related Questions & Answers
- MongoDB regular expression to match a specific record?
- Fetch specific field values in MongoDB
- Fetch specific multiple documents in MongoDB
- Using regex in MongoDB findOne()
- Query an array in MongoDB to fetch a specific value
- Fetch a specific document in MongoDB with array elements
- Usage of findOne() with MongoDB?
- How to generate ObjectID in MongoDB?
- Convert string to objectid in MongoDB?
- MongoDB query to find a specific city record from a collection
- Make nested queries in MongoDB 4 to fetch a specific document
- Find a document with ObjectID in MongoDB?
- MongoDB regular expression to fetch record with specific name “John”, instead of “john”
- Accessing array values in a MongoDB collection to fetch a specific document
- How to filter dates in MySQL to fetch date record only for a specific month?
Advertisements