Retrieving a Single Document in MongoDB: The findOne() Method
Learn how to efficiently retrieve a single document from a MongoDB collection using the findOne() method. Explore the various query operators and techniques to filter and find specific documents based on their attributes. This guide will provide you with the necessary knowledge to effectively extract individual documents from your MongoDB databases.
MongoDB: Find Single Document from Collection using findOne()
In MongoDB, collections are like tables in RDBMS, and documents are like records in those tables. The findOne()
method retrieves a single document from a collection based on specified criteria.
MongoDB provides two methods for finding documents:
findOne()
- Returns the first document that matches the specified criteria.find()
- Returns a cursor to the documents that match the criteria.
Sample Data
First, insert some documents into the employees
collection:
Insert Sample Data
db.employees.insertMany([
{ _id: 1, firstName: "John", lastName: "King", email: "john.king@abc.com", salary: 5000 },
{ _id: 2, firstName: "Sachin", lastName: "T", email: "sachin.t@abc.com", salary: 8000 },
{ _id: 3, firstName: "James", lastName: "Bond", email: "jamesb@abc.com", salary: 7500 },
{ _id: 4, firstName: "Steve", lastName: "J", email: "steve.j@abc.com", salary: 9000 },
{ _id: 5, firstName: "Kapil", lastName: "D", email: "kapil.d@abc.com", salary: 4500 },
{ _id: 6, firstName: "Amitabh", lastName: "B", email: "amitabh.b@abc.com", salary: 11000 }
])
Using findOne()
The findOne()
method returns the first document that matches the specified criteria. If no criteria are provided, it returns the first document from the collection.
Syntax
db.collection.findOne(query, projection)
Parameters:
query
: Optional. Criteria for finding the document.projection
: Optional. Fields to include or exclude in the result.
Examples
1. Find the first document in the collection:
Example: Find the First Document
db.employees.findOne()
Output:
{ _id: 1, firstName: 'John', lastName: 'King', email: 'john.king@abc.com', salary: 5000 }
2. Find a document with a specific firstName
:
Example: Find Document by First Name
db.employees.findOne({ firstName: "Kapil" })
Output:
{ _id: 5, firstName: 'Kapil', lastName: 'D', email: 'kapil.d@abc.com', salary: 4500 }
3. Find a document with a salary greater than 8000:
Example: Find Document with Salary Greater than 8000
db.employees.findOne({ salary: { $gt: 8000 } })
Output:
{ _id: 4, firstName: 'Steve', lastName: 'J', email: 'steve.j@abc.com', salary: 9000 }
4. Find a document with a specific firstName
and project only certain fields:
Example: Find Document with Projection
db.employees.findOne({ firstName: "Sachin" }, { _id: 0, firstName: 1, lastName: 1 })
Output:
{ firstName: 'Sachin', lastName: 'T' }
Note: By default, the _id
field is included in the results. To exclude it, specify { _id: 0 }
in the projection.