💧 $match:
Match specific documents using the query.
Syntax: {$match: {<query>}} i.e. the query will be an object.
Example:
{$match: {city: "New York"}};
💧 $match and $group stages together:
Remember: the $match stage will always remain before the $group stage.
db.persons.aggregate([
{$match: {favoriteFruit: "banana"}},
{$group: {_id: {age: "$age", eyeColor: "$eyeColor", fruit: "$favoriteFruit"}}}
])
Output:
{
"_id": {
"age" : NumberInt(36),
"eyeColor": "brown",
"fruit": "banana"
}
}
// ----------------------------------------------
{
"_id": {
"age" : NumberInt(26),
"eyeColor": "green",
"fruit": "banana"
}
}
But if we use the $match stage after the $group stage, then we have to use it with the output document of the group stage.
db.persons.aggregate([
{$group: {_id: {age: "$age", eyeColor: "$eyeColor"}}},
{$match: {"_id.age": {$gt: 30}}}
])
Post a Comment