- 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
MongoDB findById returning a list of documents instead of a single result? How to get only a single document?
To get only a single result, use findOne() and fetch on the basis of id. Let us create a collection with documents −
> db.demo340.insertOne({_id:1,"Name":"Chris",Age:21}); { "acknowledged" : true, "insertedId" : 1 } > db.demo340.insertOne({_id:2,"Name":"David",Age:23}); { "acknowledged" : true, "insertedId" : 2 } > db.demo340.insertOne({_id:3,"Name":"Bob",Age:20}); { "acknowledged" : true, "insertedId" : 3 } > db.demo340.insertOne({_id:4,"Name":"Sam",Age:19}); { "acknowledged" : true, "insertedId" : 4 }
Display all documents from a collection with the help of find() method −
> db.demo340.find();
This will produce the following output −
{ "_id" : 1, "Name" : "Chris", "Age" : 21 } { "_id" : 2, "Name" : "David", "Age" : 23 } { "_id" : 3, "Name" : "Bob", "Age" : 20 } { "_id" : 4, "Name" : "Sam", "Age" : 19 }
Here is the query to findby id −
> db.demo340.findOne({_id:1});
This will produce the following output −
{ "_id" : 1, "Name" : "Chris", "Age" : 21 }
Advertisements