How is it possible that accumulator within $project stage give a single value?

Dear colleagues!

How is it possible that on this screenshot from video lesson they got a single value using accumulator $max within $project stage?


I thought the only way to get the single value for all documents is to use $group stage with _id:null.
I have tried to use $max within $project stage and as I aspected it gives multiple result - with one value for each document. my query was db.movies.aggregate([

{
$project: {
_id: 0,
highest_rating: { $max: “$imdb.rating” },
lowest_rating: { $min: “$imdb.rating” }
}
}
])

So how is it possible that in video they got the single value using $group stage?

thank you very much in advance!

‘trends’ is an array and ‘trends.avg_high_tmp’ is an element with an array
In project stage $max takes input as an array.
But in group stage $max works as aggregation function to lookup all the documents and gives the result

Exactly, BUT then after $max was applied to an array in $project stage, the result should contain many values for each document in collection!
look down at screenshot please


trends.avg_high_tmp is defined for every month within the document (in array “trends”). so then we apply $max in $project stage, it should return the maximal avg.temperature among all months in array but for every document id. So I expect to see as many results, as we have documents in collections - the one value for every document.
But on video they get only one value for whole collection! how is it possible?

It could happen if there is only 1 document in the collection.

MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.icecream_data.count()
1

2 Likes

thank you very much ! it explains everything!