Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 instead of a list when querying by ID in MongoDB, use the findOne() method instead of find(). The findOne() method returns exactly one document that matches your query criteria.
Syntax
db.collection.findOne({_id: ObjectId("id_value")})
Sample Data
Let us create a collection with documents ?
db.demo340.insertMany([
{_id: 1, "Name": "Chris", Age: 21},
{_id: 2, "Name": "David", Age: 23},
{_id: 3, "Name": "Bob", Age: 20},
{_id: 4, "Name": "Sam", Age: 19}
]);
{
"acknowledged": true,
"insertedIds": {
"0": 1,
"1": 2,
"2": 3,
"3": 4
}
}
Display all documents from a collection with the help of find() method ?
db.demo340.find();
{ "_id": 1, "Name": "Chris", "Age": 21 }
{ "_id": 2, "Name": "David", "Age": 23 }
{ "_id": 3, "Name": "Bob", "Age": 20 }
{ "_id": 4, "Name": "Sam", "Age": 19 }
Example: Get Single Document by ID
Here is the query to find by id using findOne() ?
db.demo340.findOne({_id: 1});
{ "_id": 1, "Name": "Chris", "Age": 21 }
Key Differences
| Method | Returns | Use Case |
|---|---|---|
| find() | Cursor (array-like) | Multiple documents |
| findOne() | Single document object | One document only |
Conclusion
Use findOne() when you need exactly one document result. It returns the document object directly instead of a cursor, eliminating the need to iterate through results.
Advertisements
