

- 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
How to find only a single document satisfying the criteria in MongoDB?
To find only a single document, use findOne() in MongoDB. Let us create a collection with documents −
> db.demo116.insertOne({"EmployeeId":101,"EmployeeName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2eff98d8f64a552dae635b") } > db.demo116.insertOne({"EmployeeId":102,"EmployeeName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2eff9fd8f64a552dae635c") } > db.demo116.insertOne({"EmployeeId":103,"EmployeeName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2effa5d8f64a552dae635d") } > db.demo116.insertOne({"EmployeeId":102,"EmployeeName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2effb7d8f64a552dae635e") }
Display all documents from a collection with the help of find() method −
> db.demo116.find();
This will produce the following output −
{ "_id" : ObjectId("5e2eff98d8f64a552dae635b"), "EmployeeId" : 101, "EmployeeName" : "John" } { "_id" : ObjectId("5e2eff9fd8f64a552dae635c"), "EmployeeId" : 102, "EmployeeName" : "Bob" } { "_id" : ObjectId("5e2effa5d8f64a552dae635d"), "EmployeeId" : 103, "EmployeeName" : "David" } { "_id" : ObjectId("5e2effb7d8f64a552dae635e"), "EmployeeId" : 102, "EmployeeName" : "Mike" }
Following is the query to find only a single document in MongoDB −
> db.demo116.findOne({"EmployeeId":102});
This will produce the following output −
{ "_id" : ObjectId("5e2eff9fd8f64a552dae635c"), "EmployeeId" : 102, "EmployeeName" : "Bob" }
- Related Questions & Answers
- Retrieve only a single document specifying a criteria in MongoDB?
- Update only a single document in MongoDB
- Remove only a single document in MongoDB
- Increment only a single value in MongoDB document?
- Update only a single MongoDB document without deleting any date
- MongoDB findOneAndUpdate() to update a single document
- MongoDB findById returning a list of documents instead of a single result? How to get only a single document?
- Remove only one document in MongoDB?
- Updating a MongoDB document and adding new keys only in the first document?
- Decrement only a single value in MongoDB?
- MongoDB query to return only embedded document?
- Update only a specific value in a MongoDB document
- How to find a certain element in the MongoDB embedded document?
- Selecting only a single field from MongoDB?
- Find value in a MongoDB Array with multiple criteria?
Advertisements