MongoDB query operators are used to specify criteria in queries and to perform a variety of operations, such as comparison, logical operations, and element evaluation.
- $eq: Matches values that are equal to a specified value.
- $gt: Matches values that are greater than a specified value.
- $lt: Matches values that are less than a specified value.
- $in: Matches any of the values specified in an array.
- $and: Joins query clauses with a logical AND.
- $or: Joins query clauses with a logical OR.
The $regex
operator provides regular expression capabilities for pattern matching strings in queries.
{ "name": { "$regex": "^A", "$options": "i" } }
Q3. Explain how to use the $regex operator to find documents where the 'name' field starts with 'apple'.
db.products.find({ name: /^apple/ });
Projection in MongoDB is the process of selecting specific fields to return in query results. It is useful for:
- Reducing the amount of data transferred over the network.
- Improving query performance by retrieving only necessary data.
db.collection.find({ "status": "active" }, { "name": 1, "email": 1, "_id": 0 })
To exclude specific fields in a projection, set their values to 0.
db.collection.find({}, { "password": 0, "creditCardNumber": 0 })
This query returns all fields except password and creditCardNumber.
The $slice
operator limits the number of elements in an array returned by a query.
db.collection.find({}, { "comments": { "$slice": 5 } })
The $elemMatch projection operator limits the contents of an array field to contain only the first element that matches the specified query condition.
db.collection.find(
{ "results": { "$elemMatch": { "score": { "$gt": 80 } } } },
{ "results": { "$elemMatch": { "score": { "$gt": 80 } } } }
)
This query matches documents where the results
array contains at least one element with a score
greater than 80, and projects only that element.
Q7. What is the purpose of the $ operator in projections, and how does it differ from its use in updates?
In projections, the $
operator limits the output to contain only the first array element that matches the query condition. In updates, it identifies the first matching element in an array for modification.
db.collection.find(
{ "results.score": { "$gt": 80 } },
{ "results.$": 1 }
)
This query returns documents where results.score is greater than 80, projecting only the first matching results array element.
db.collection.updateOne(
{ "results.score": { "$gt": 80 } },
{ "$set": { "results.$.score": 90 } }
)
This query updates the score
to 90 for the first element in the results
array that matches the condition score > 80
.