$project and accumulator

$avg returns multiple values for each document not a single document

Hi,

Could you send me your query please?

José Carlos

If I use :
db.movies.aggregate( [ { $project: { _id:0, max_rating: {$max:"$imdb.rating" } } } ] )

here $max function is working over an a document and not carrying the values forward!!!
How to use $max function as group accumulator?

@ferb0, you want to use $max inside a $group stage, not a $project stage.

1 Like

Hi,

You would need a $group stage, e.g. max rating by year:

db.movies.aggregate([{$group: {_id: "$year", max_rating: {$max: "$imdb.rating"}}}, {$project: {_id: 0, year: "$_id", rating: "$max_rating"}}])

Recall that you can use _id: null to apply the group expression to all the documents as if they were a single group.

José Carlos

1 Like

I tried the detailed answer for this lab on compass and it seems that the match expression won’t work on compass.

Hi @isaelfeliciano,

Could you kindly let us know which lab do you refer to?

José Carlos

The lab which this post is for, $project and accumulator.

Hi,

I believe the lab is $group and accumulators, not $project and accumulators. Will check if there’s a problem with the regular expression in Compass.

José Carlos

Hi @isaelfeliciano,

You are right, I was not able to run the $match stage in Compass, I believe the cause is the regular expression. Will pass this to the team to look into it.

José Carlos

1 Like

Thank you for looked into it

Dear Mr Carlos,

May I ask you a question please.
How is it possible that on this screenshot 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 values 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!