- 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
Usage of findOne() with MongoDB?
The findOne() in MongoDB returns only a single document. Let us create a collection with documents −
> db.demo230.insertOne({"FirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc4d2f4cebbeaebec513e") } > db.demo230.insertOne({"FirstName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc4d5f4cebbeaebec513f") } > db.demo230.insertOne({"FirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc4dbf4cebbeaebec5140") } > db.demo230.insertOne({"FirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc4dff4cebbeaebec5141") } > db.demo230.insertOne({"FirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc4e1f4cebbeaebec5142") }
Display all documents from a collection with the help of find() method −
> db.demo230.find();
This will produce the following output −
{ "_id" : ObjectId("5e3fc4d2f4cebbeaebec513e"), "FirstName" : "Chris" } { "_id" : ObjectId("5e3fc4d5f4cebbeaebec513f"), "FirstName" : "Bob" } { "_id" : ObjectId("5e3fc4dbf4cebbeaebec5140"), "FirstName" : "Chris" } { "_id" : ObjectId("5e3fc4dff4cebbeaebec5141"), "FirstName" : "David" } { "_id" : ObjectId("5e3fc4e1f4cebbeaebec5142"), "FirstName" : "David" }
Following is the query for findOne() in MongoDB −
> db.demo230.findOne({"FirstName":"David"});
This will produce the following output. Returns only one document even if we had more than one document with “FirstName David” −
{ "_id" : ObjectId("5e3fc4dff4cebbeaebec5141"), "FirstName" : "David" }
Advertisements