Advanced MongoDB Query Features
1. What is the purpose of query operators in MongoDB?
Query operators refine queries by specifying conditions for data retrieval. They allow developers to build more precise and complex queries, enabling actions like comparisons, logical operations, pattern matching, and existence checks.
Example:
Retrieve documents where the age is greater than 25:
db.users.find({ age: { $gt: 25 } })
2. Explain the $eq, $ne, $gt, $gte, $lt, and $lte operators.
These operators perform conditional comparisons on fields in a query.
-
$eq: Matches documents where a field is equal to a specified value.
{ age: { $eq: 25 } }
-
$ne: Matches documents where a field is not equal to a specified value.
{ age: { $ne: 25 } }
-
$gt: Matches documents where a field is greater than a specified value.
{ age: { $gt: 25 } }
-
$gte: Matches documents where a field is greater than or equal to a specified value.
{ age: { $gte: 25 } }
-
$lt: Matches documents where a field is less than a specified value.
{ age: { $lt: 25 } }
-
$lte: Matches documents where a field is less than or equal to a specified value.
{ age: { $lte: 25 } }
3. How do you use the $regex operator for pattern matching?
The $regex operator matches strings against a regular expression pattern.
Example: Find users whose names start with "A":
db.users.find({ name: { $regex: "^A" } })
- Flags like
ican be added for case-insensitivity:
{ name: { $regex: "^A", $options: "i" } }
4. What is the $in operator used for?
The $in operator matches documents where a field’s value is within a specified array of values.
Example: Find users with specific ages:
db.users.find({ age: { $in: [25, 30, 35] } })
5. Explain the $exists operator.
The $exists operator checks whether a field exists in a document.
Examples:
- Documents where the field
emailexists:
db.users.find({ email: { $exists: true } })
- Documents where the field
phonedoes not exist:
db.users.find({ phone: { $exists: false } })
6. How do logical operators like $or and $and work in MongoDB?
-
$or: Matches documents that satisfy any condition in the array. Example: Users aged 25 or named "Alice":
db.users.find({ $or: [{ age: 25 }, { name: "Alice" }] })
-
$and: Matches documents that satisfy all conditions in the array. Example: Users aged 25 and living in "New York":
db.users.find({ $and: [{ age: 25 }, { city: "New York" }] })
7. What is a projection in MongoDB?
A projection specifies which fields to include or exclude in the query results.
Syntax:
db.collection.find(query, projection)
Examples:
- Include only
nameandage:
db.users.find({}, { name: 1, age: 1 })
- Exclude the
_idfield:
db.users.find({}, { _id: 0, name: 1 })
8. How do you sort query results in MongoDB?
The sort method orders the query results based on specified fields.
Syntax:
db.collection.find().sort({ field: order })
- 1: Ascending order.
- -1: Descending order.
Example: Sort users by age (ascending) and name (descending):
db.users.find().sort({ age: 1, name: -1 })
9. Explain the limit and skip methods in queries.
-
limit: Restricts the number of documents returned by the query. Example: Return the first 5 users:
db.users.find().limit(5)
-
skip: Skips a specified number of documents in the query result. Example: Skip the first 5 users and return the next 5:
db.users.find().skip(5).limit(5)
These methods are often combined for pagination.
40. How do you perform aggregation in MongoDB?
Aggregation processes data and performs operations like filtering, grouping, and transforming. It uses the aggregate method and a pipeline of stages.
Syntax:
db.collection.aggregate([pipeline_stage1, pipeline_stage2, ...])
Common Stages:
-
$match: Filters documents (similar tofind). -
$group: Groups documents by a field and performs calculations likesum,avg, etc. -
$project: Modifies the structure of the output.
Example: Find the average age of users grouped by city:
db.users.aggregate([
{ $group: { _id: "$city", avgAge: { $avg: "$age" } } }
])
These features provide powerful tools for querying and transforming data in MongoDB, making it flexible for a wide range of applications.
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
Top comments (0)