- 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 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" }
Advertisements