Lecture Notes Of Day 6:
MongoDB CRUD
Operations – Part 2 (Find)
Objective:
- Learn
how to query MongoDB using the find() method.
- Understand
how to filter documents based on various conditions.
Outcome:
By the end of the class,
students will be able to query MongoDB collections using the find() method and
apply different filters and operators to retrieve specific documents.
Introduction to the find()
Method
In MongoDB, the find()
method is used to query the database and retrieve documents from a collection.
It is one of the most important operations when interacting with MongoDB.
db.collection.find(query, projection)
- query:
A document specifying the conditions to match documents.
- projection:
(Optional) A document specifying the fields to return.
1. Basic Query with find()
To retrieve all documents
in a collection, simply call find() without any parameters.
Example:
db.students.find()
This will return all
documents in the students collection.
2. Querying with a Filter
You can pass a query
document to find() to filter the documents based on certain conditions. MongoDB
uses a flexible query language that allows you to filter documents by matching
field values.
Example:
db.students.find({ age: 21 })
This query returns all
documents where the age field is equal to 21.
3. Using Comparison
Operators
MongoDB supports a
variety of comparison operators that allow for more complex queries. These
operators include:
- $eq:
Equal to
- $ne:
Not equal to
- $gt:
Greater than
- $gte:
Greater than or equal to
- $lt:
Less than
- $lte:
Less than or equal to
- $in:
Matches any of the values in an array
- $nin:
Matches none of the values in an array
Example:
db.students.find({ age: { $gt: 18 } })
This will return all
documents where the age field is greater than 18.
4. Querying with Multiple
Conditions
You can combine multiple
conditions within a query by using logical operators such as $and, $or, and $not.
Example (using $and):
db.students.find({ age: { $gt: 18 }, grade: { $gte: 75 } })
This returns all
documents where the age is greater than 18 and the grade is greater than
or equal to 75.
Example (using $or):
db.students.find({ $or: [{ age: 21 }, { grade: { $gte: 85 } }] })
This returns all
documents where the age is 21 or the grade is greater than or equal to 85.
5. Querying Nested Fields
If your documents have
nested fields (e.g., embedded objects), you can query them using dot notation.
Example:
db.students.find({ "address.city": "New York" })
This query returns all
documents where the address.city is New York.
6. Limiting the Number of
Results
To limit the number of
documents returned by a query, use the limit() method.
Example:
db.students.find().limit(5)
This will return only the
first 5 documents in the students collection.
7. Sorting Results
You can sort the query
results using the sort() method. The argument is a document where the field
names are specified, and the values define the sort order:
- 1
for ascending order
- -1
for descending order
Example:
db.students.find().sort({ age: 1 })
This sorts the documents
by the age field in ascending order.
8. Projecting Specific
Fields
You can use the projection
argument in the find() method to specify which fields to return in the result.
You can either include or exclude fields.
Example (including
specific fields):
db.students.find({}, { name: 1, age: 1 })
This returns only the name
and age fields from all documents.
Example (excluding
specific fields):
db.students.find({}, { _id: 0 })
This excludes the _id
field from the result.
9. Handling Results
The find() method returns
a cursor, not an array of documents. You can either iterate over the cursor or
convert it to an array using .toArray().
Example (using forEach to
iterate over the results):
db.students.find().forEach(student => {
print(student.name);
});
Example (converting to an
array):
db.students.find().toArray()
10. Practical Example
Consider a collection of students
with the following fields:
{
"_id": 1,
"name": "John Doe",
"age": 21,
"grade": 80,
"address": { "city": "New
York", "zip": "10001" }
}
You can perform the
following queries:
1.
Find all students aged greater than 18:
db.students.find({ age: { $gt: 18 } })
2.
Find students in New York:
db.students.find({ "address.city": "New York" })
3.
Find students with a grade greater than or
equal to 75 and age less than 25:
db.students.find({ grade: { $gte: 75 }, age: { $lt: 25 } })
4.
Limit the result to 2 documents:
db.students.find().limit(2)
5.
Sort the results by age in descending
order:
db.students.find().sort({ age: -1 })
Conclusion
- The
find() method in MongoDB is a powerful tool for querying documents in a
collection.
- By
using filters, operators, and projections, you can retrieve very specific
data from your MongoDB database.
- Mastering
these CRUD operations (especially find()) is key to working efficiently
with MongoDB.
Practice Exercises
1.
Write a query to find all documents where
the age is greater than or equal to 25.
2.
Retrieve only the name and grade fields of
students who have a grade greater than 90.
3.
Use the $or operator to find students who
are either in New York or have a grade above 85.
4.
Limit your query to show only the first 3
students ordered by their name in ascending order.
These exercises will help
you get comfortable with querying MongoDB and using various operators.
