MongoDB query operations
MongoDB uses JavaScript-like syntax for queries.
Basic Query Syntax:
db.collection_name.find(query, projection)
o query: Filters the data (optional).
o projection: Specifies fields to return (optional).
db.users.find() To retrieve all documents in a collection.
Insert Documents
db.users.insertMany([
{ name: "aatif", age: 35, city: "Rampur", salary: 5000 },
{ name: "prashant", age: 30, city: "Ghaziabad", salary: 7000 },
{ name: " abhishek ", age: 35, city: "Prayagraj", salary: 6000 },
{ name: "ashish", age: 40, city: "kanpur", salary: 8000 }])
Comparison Operators
$gt: Greater than
$gte: Greater than or equal to $lte: Less than or equal to
$lt: Less than $ne: Not equal to
db.users.find({
age: { $gte: 25, $lte: 35 }
})
Logical Operators
Find users whose age is greater than 25 or their name is “aatif”:
db.users.find ({
$or: [ { age: { $gt: 25 } },{ name: "aatif" }]})
Query with Filters
db.users.find({ name: "Alice" })
db.users.find({ age: { $gt: 25 } })
Query with Projections
In MongoDB, projection is a feature that allows you to specify which fields of a document
should be included or excluded in the result of a query.
db.users.find({}, { name: 1, age: 1, _id: 0 }) => Return only the name and age of all
users. The _id field is included by default, so setting it to 0 excludes it.
db.users.find({ age: 35 }, { name: 1, city: 1, _id: 0 })
Querying Arrays
db.users.find({ hobbies: "coding" })
db.users.find({ hobbies: { $all: ["reading", "traveling"] } }) Query users who have both
"reading" and "traveling" as hobbies:
db.users.find({ hobbies: { $nin: ["reading", "traveling"] } }) Don’t have either
db.users.find({ hobbies: { $not: { $all: ["reading", "traveling"] } } })}) not contain both
Sorting
The sort() method sorts the result set. 1 for ascending, -1 for descending.
Sort users by age in ascending/ descending order:
db.users.find().sort({ age: 1 })
db.users.find().sort({ name: -1 })
Limit and Skip
limit() restricts the number of documents returned, and skip() skips a
specified number of documents.
db.users.find().limit(2) Retrieve the first two users
db.users.find().skip(2).limit(2) Skip the first two users and return the next two
Updating Documents
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
)
Update multiple users' hobby to "coding"
db.users.updateMany(
{ age: { $gt: 25 } },
{ $set: { hobbies: ["coding"] } }
)
Deleting Documents
db.users.deleteOne({ name: "Bob" })
db.users.deleteMany({ age: { $gt: 30 } })
Aggregation Queries
For more complex queries, MongoDB supports aggregation pipelines.
Group users by age and get the count of users in each age group:
Match (Filter Data):
db.users.aggregate([
{ $match: { city: "Los Angeles" } }
]) retrieve all from collection where the city field is equal to "Los Angeles"
Project (Select Specific Fields):
db.users.aggregate([
{ $project: { _id: 0, name: 1, city: 1 } }
])
Group and Sum
Group users by city and calculate the total salary for each city.
db.users.aggregate([
{ $group: { _id: "$city", totalSalary: { $sum: "$salary" } } }
])
Group and Average
Group users by city and calculate the average salary for each city.
db.users.aggregate([
{ $group: { _id: "$city", averageSalary: { $avg: "$salary" } } }
])
Group and Count
Group users by city and count the number of users in each city.
db.users.aggregate([
{ $group: { _id: "$city", userCount: { $sum: 1 } } }
])
grouping the documents in the users collection by the city field, and for each city,
counting the number of users.
Sort Results
Sort the cities by total salary in descending order.
db.users.aggregate([
{ $group: { _id: "$city", totalSalary: { $sum: "$salary" } } },
{ $sort: { totalSalary: -1 } }
])
Match and Group
First, filter users who earn more than 6000, then group them by city and calculate
the total salary.
db.users.aggregate([
{ $match: { salary: { $gt: 6000 } } },
{ $group: { _id: "$city", totalSalary: { $sum: "$salary" } } }
])
Group, Filter, and Project
Filter users with an age greater than 30. Group them by city. Include the total
number of users and the maximum salary per city.
db.users.aggregate([
{ $match: { age: { $gt: 30 } } }, // Step 1: Filter users with age > 30
{ $group: { _id: "$city", // Step 2: Group by city
totalUsers: { $sum: 1 }, // Count users
maxSalary: { $max: "$salary" } } }, // Find max salary in each group
{ $project: { _id: 1, totalUsers: 1, maxSalary: 1 } } // Step 3: Project only necessary fields
])
Match, Group, Sort, and Limit
Filter users who are from Los Angeles. Group them by city. Sort the groups by the
number of users in descending order. Return only the first result.
db.users.aggregate([
{ $match: { city: "Los Angeles" } }, // Step 1: Filter by city
{ $group: { _id: "$city", totalUsers: { $sum: 1 } } }, // Step 2: Group by city
{ $sort: { totalUsers: -1 } }, // Step 3: Sort by totalUsers
{ $limit: 1 } // Step 4: Limit to 1 result
])