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 function to return a specific data/value?
To return a specific data/value in MongoDB, use the findOne() method. The findOne() method returns the first document that satisfies the specified query criteria from the collection.
Syntax
db.collection.findOne(query, projection)
Create Sample Data
Let us create a collection with documents ?
db.demo473.insertMany([
{
"_id": ObjectId(),
"Name": "Chris",
"details": {
"X-Coordinate": 10,
"Y-Coordinate": 15
}
},
{
"_id": ObjectId(),
"Name": "Bob",
"details": {
"X-Coordinate": 11,
"Y-Coordinate": 12
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e805a07b0f3fa88e227907d"),
ObjectId("5e805a07b0f3fa88e227907e")
]
}
Display All Documents
Display all documents from the collection with the help of find() method ?
db.demo473.find();
{ "_id": ObjectId("5e805a07b0f3fa88e227907d"), "Name": "Chris", "details": { "X-Coordinate": 10, "Y-Coordinate": 15 } }
{ "_id": ObjectId("5e805a07b0f3fa88e227907e"), "Name": "Bob", "details": { "X-Coordinate": 11, "Y-Coordinate": 12 } }
Example: Return Specific Data Using findOne()
Following is the query to return a specific document with MongoDB findOne() function ?
db.demo473.findOne({ "details.X-Coordinate": 11 });
{
"_id": ObjectId("5e805a07b0f3fa88e227907e"),
"Name": "Bob",
"details": {
"X-Coordinate": 11,
"Y-Coordinate": 12
}
}
Key Points
-
findOne()returns only the first matching document, not all matches. - Use dot notation to query nested fields like
"details.X-Coordinate". - If no document matches,
findOne()returnsnull.
Conclusion
The findOne() method is perfect for retrieving a single document that matches specific criteria. It's more efficient than find() when you only need one result.
Advertisements
