- 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
Retrieve only a single document specifying a criteria in MongoDB?
Use findOne() in MongoDB for this. The findOne() returns one document that satisfies the specified query criteria on the collection.
Let us create a collection with documents −
> db.demo596.insertOne({_id:1,"FirstName":"John","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : 1 } > db.demo596.insertOne({_id:2,"FirstName":"John","LastName":"Doe"}); { "acknowledged" : true, "insertedId" : 2 } > db.demo596.insertOne({_id:3,"FirstName":"Chris","LastName":"Brown"}); { "acknowledged" : true, "insertedId" : 3 } > db.demo596.insertOne({_id:4,"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : 4 }
Display all documents from a collection with the help of find() method −
> db.demo596.find();
This will produce the following output −
{ "_id" : 1, "FirstName" : "John", "LastName" : "Smith" } { "_id" : 2, "FirstName" : "John", "LastName" : "Doe" } { "_id" : 3, "FirstName" : "Chris", "LastName" : "Brown" } { "_id" : 4, "FirstName" : "David", "LastName" : "Miller" }
Here is the query to retrieve only a single document −
> db.demo596.findOne({"FirstName":"John"});
This will produce the following output −
{ "_id" : 1, "FirstName" : "John", "LastName" : "Smith" }
Advertisements