MongoDB Read Operations
Introduction
Read operations in MongoDB allow you to retrieve data from your database collections. Whether you need to fetch a single document, multiple documents matching specific criteria, or analyze data with complex queries, MongoDB provides powerful tools to access your information efficiently.
In this tutorial, you'll learn how to:
- Query documents using the
find()
method - Structure queries with various operators
- Use projections to retrieve only needed fields
- Work with cursors for large result sets
- Perform advanced queries for real-world scenarios
Basic Read Operations
The find()
Method
The most fundamental way to query data in MongoDB is using the find()
method. This method returns a cursor to the matching documents.
Syntax
db.collection.find(query, projection)
Where:
query
(optional): Specifies selection criteria using query operatorsprojection
(optional): Specifies which fields to return in the matching documents
Finding All Documents
To retrieve all documents in a collection:
db.products.find()
This returns all documents in the "products" collection.
Finding Specific Documents
To find documents that match specific criteria:
db.products.find({ category: "Electronics" })
This returns all documents where the category field equals "Electronics".
Example Output
If you run the above query, the output might look like:
[
{
"_id": ObjectId("60a8f6d86b12b331acf25432"),
"name": "Smartphone",
"category": "Electronics",
"price": 699.99,
"stock": 50
},
{
"_id": ObjectId("60a8f6d86b12b331acf25433"),
"name": "Laptop",
"category": "Electronics",
"price": 1299.99,
"stock": 25
}
]
The findOne()
Method
If you need only the first matching document, use findOne()
:
db.products.findOne({ category: "Electronics" })
This returns only the first document that matches the criteria:
{
"_id": ObjectId("60a8f6d86b12b331acf25432"),
"name": "Smartphone",
"category": "Electronics",
"price": 699.99,
"stock": 50
}
Query Operators
MongoDB provides query operators that allow you to specify conditions for your queries.
Comparison Operators
Operator | Description |
---|---|
$eq | Equal to |
$gt | Greater than |
$gte | Greater than or equal to |
$lt | Less than |
$lte | Less than or equal to |
$ne | Not equal to |
$in | Matches any value in an array |
$nin | Does not match any value in an array |
Examples
Finding products with price greater than $1000:
db.products.find({ price: { $gt: 1000 } })
Finding products with prices between 1500:
db.products.find({ price: { $gte: 500, $lte: 1500 } })
Finding products that are either smartphones or laptops:
db.products.find({ name: { $in: ["Smartphone", "Laptop"] } })
Logical Operators
Operator | Description |
---|---|
$and | Logical AND |
$or | Logical OR |
$not | Logical NOT |
$nor | Logical NOR (neither condition is true) |
Examples
Finding products in Electronics category with price less than $800:
db.products.find({
$and: [
{ category: "Electronics" },
{ price: { $lt: 800 } }
]
})
A shorthand for the AND condition:
db.products.find({ category: "Electronics", price: { $lt: 800 } })
Finding products that are either in Electronics category or have a price less than $100:
db.products.find({
$or: [
{ category: "Electronics" },
{ price: { $lt: 100 } }
]
})
Projections
Projections allow you to control which fields are returned in the query results. This helps reduce network overhead and processing time.
Syntax
db.collection.find(query, { field1: 1, field2: 1 }) // Include only these fields
db.collection.find(query, { field1: 0, field2: 0 }) // Exclude these fields
Note: You cannot mix inclusion and exclusion in the same projection object, except for the _id
field.
Examples
Return only the name and price fields:
db.products.find({ category: "Electronics" }, { name: 1, price: 1 })
Output:
[
{
"_id": ObjectId("60a8f6d86b12b331acf25432"),
"name": "Smartphone",
"price": 699.99
},
{
"_id": ObjectId("60a8f6d86b12b331acf25433"),
"name": "Laptop",
"price": 1299.99
}
]
Return all fields except stock:
db.products.find({ category: "Electronics" }, { stock: 0 })
Exclude _id field and only include name and price:
db.products.find({ category: "Electronics" }, { _id: 0, name: 1, price: 1 })
Output:
[
{
"name": "Smartphone",
"price": 699.99
},
{
"name": "Laptop",
"price": 1299.99
}
]