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() returns null.

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.

Updated on: 2026-03-15T03:05:58+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements