[MongoDB] how to reference fields/keys
How to reference fields/keys
How did I encounter this?
While learning MongoDB's aggregation pipeline, I noticed an inconsistency when referencing fields in some stages.
db.movies.aggregate([
{
$match: { year: {$gte:2000}}
},
{
$count: 'movies_since_2000'
}
])
db.movies.aggregate([
{
$sort: {'year':1, 'title':1}
},
{
$group: {
_id: '$year',
firstMovie: {$first: '$title'},
lastMovie: {$last: '$title'},
}
}
])
in the stage of $match, the field, year is referenced directly, but in the stage of $sort, year is surrounded by ''. However, in the stage of $group, year is referenced with '$'
Syntax
In mongoDB's aggregation stages, there are 2 types of stages: Document-shaped stages and Expression-based stages.
Document-shaped stages
$match or $sort, are Document-shaped stages. They pass or filter the entire document based on certain criteria but they don't need to dynamically compute new fields. When using them, fields or keys can be referenced without $, even ''(when the key is a simple identifier).
Expression-based stages
$group or $project are Expression-based stages. They compute or transform data using MongoDB's expression language. When using them, fields or keys must be referenced with $''
Comments
Post a Comment