MongoDB Query Operators
There are many query operators that can be used to compare and reference document fields.
Comparison
The following operators can be used in queries to compare values:
$eq
: Values are equal$ne
: Values are not equal$gt
: Value is greater than another value$gte
: Value is greater than or equal to another value$lt
: Value is less than another value$lte
: Value is less than or equal to another value$in
: Value is matched within an array
Logical
The following operators can logically compare multiple queries.
$and
: Returns documents where both queries match$or
: Returns documents where either query matches$nor
: Returns documents where both queries fail to match$not
: Returns documents where the query does not match
Evaluation
The following operators assist in evaluating documents.
$regex
: Allows the use of regular expressions when evaluating field values$text
: Performs a text search$where
: Uses a JavaScript expression to match documents
MongoDB Update Operators
There are many update operators that can be used during document updates.
Fields
The following operators can be used to update fields:
$currentDate
: Sets the field value to the current date$inc
: Increments the field value$rename
: Renames the field$set
: Sets the value of a field$unset
: Removes the field from the document
Array
The following operators assist with updating arrays.
$addToSet
: Adds distinct elements to an array$pop
: Removes the first or last element of an array$pull
: Removes all elements from an array that match the query$push
: Adds an element to an array
Aggregation Pipelines
Aggregation operations allow you to group, sort, perform calculations, analyze data, and much more.
Aggregation pipelines can have one or more “stages”. The order of these stages are important. Each stage acts upon the results of the previous stage.
Example
db.posts.aggregate([
// Stage 1: Only find documents that have more than 1 like
{
$match: { likes: { $gt: 1 } }
},
// Stage 2: Group documents by category and sum each categories likes
{
$group: { _id: "$category", totalLikes: { $sum: "$likes" } }
}
])
For more details look to aggregate group
Aggregation $limit
This aggregation stage limits the number of documents passed to the next stage.
Example
In this example, we are using the “movies” as collection name
db.movies.aggregate([ { $limit: 1 } ])
For more details look to aggregate limit
Aggregation $project
This aggregation stage passes only the specified fields along to the next aggregation stage.
This is the same projection that is used with the find()
method.
Example
In this example, we are using the “restaurants” collection
db.restaurants.aggregate([ { $project: { "name": 1, "cuisine": 1, "address": 1 } }, { $limit: 5 } ])
This will return the documents but only include the specified fields.
Notice that the _id
field is also included. This field is always included unless specifically excluded.
We use a 1
to include a field and 0
to exclude a field.
Note: You cannot use both 0 and 1 in the same object. The only exception is the _id
field. You should either specify the fields you would like to include or the fields you would like to exclude.
for more detail look to $project (aggregation)
Aggregation $sort
This aggregation stage groups sorts all documents in the specified sort order.
Remember that the order of your stages matters. Each stage only acts upon the documents that previous stages provide.
Example
In this example, we are using the “sample_airbnb” Collection
db.listingsAndReviews.aggregate([
{
$sort: { "accommodates": -1 }
},
{
$project: {
"name": 1,
"accommodates": 1
}
},
{
$limit: 5
}
])
This will return the documents sorted in descending order by the accommodates
field.
The sort order can be chosen by using 1
or -1
. 1
is ascending and -1
is descending.
More detail look to $sort (aggregation)
Aggregation $match
This aggregation stage behaves like a find. It will filter documents that match the query provided.
Using $match
early in the pipeline can improve performance since it limits the number of documents the next stages must process.
Example
In this example, we are using the “listingsAndReviews
” collection
db.listingsAndReviews.aggregate([ { $match : { property_type : "House" } }, { $limit: 2 }, { $project: { "name": 1, "bedrooms": 1, "price": 1 }} ])
This will only return documents that have the property_type
of “House”.
More detail look to $match (aggregation)
Aggregation $addFields
This aggregation stage adds new fields to documents.
Example
In this example, we are using the “restaurants” collection.
db.restaurants.aggregate([ { $addFields: { avgGrade: { $avg: "$grades.score" } } }, { $project: { "name": 1, "avgGrade": 1 } }, { $limit: 5 } ])
This will return the documents along with a new field, avgGrade
, which will contain the average of each restaurants grades.score
The $addFields
stage is equivalent to a $project
stage that explicitly specifies all existing fields in the input documents and adds the new fields.
More detail look to $addFields (aggregation)
Aggregation $count
This aggregation stage counts the total amount of documents passed from the previous stage.
Example
In this example, we are using the “restaurants” collection.
db.restaurants.aggregate([
{
$match: { "cuisine": "Chinese" }
},
{
$count: "totalChinese"
}
])
This will return the number of documents at the $count
stage as a field called “totalChinese”.
More detail look to $count (aggregation)
Aggregation $lookup
This aggregation stage performs a left outer join to a collection in the same database.
There are four required fields:
from
: The collection to use for lookup in the same databaselocalField
: The field in the primary collection that can be used as a unique identifier in thefrom
collection.foreignField
: The field in thefrom
collection that can be used as a unique identifier in the primary collection.as
: The name of the new field that will contain the matching documents from thefrom
collection.
Example
In this example, we are using the “Comments” collection.
db.comments.aggregate([
{
$lookup: {
from: "movies",
localField: "movie_id",
foreignField: "_id",
as: "movie_details",
},
},
{
$limit: 1
}
])
This will return the movie data along with each comment.
More look to $lookup (aggregation)
Aggregation $out
This aggregation stage writes the returned documents from the aggregation pipeline to a collection.
The $out
stage must be the last stage of the aggregation pipeline.
Example
In this example, we are using the “listingsAndReviews
” collection.
db.listingsAndReviews.aggregate([
{
$group: {
_id: "$property_type",
properties: {
$push: {
name: "$name",
accommodates: "$accommodates",
price: "$price",
},
},
},
},
{ $out: "properties_by_type" },
])
The first stage will group properties by the property_type
and include the name
, accommodates
, and price
fields for each. The $out
stage will create a new collection called properties_by_type
in the current database and write the resulting documents into that collection.
More detail look to $out (aggregation)
Conclusion
In this post I have explored MongoDB, query operators, Fields, arrays, aggregation piplines, such as group, limit, project, macht, addfileds, lookup, out and sort.
In my next post I will explore MongoDB Indexing Search validation
This post is part of MongoDB-Step by step.