Formatting results of accumulator function

Hello,

in chapter 3, we are asked to compute the average, min, max,… of imdb.rating. My code works fine and I get the results. However, I thought it would be fancy to have already truncated results to the 4th digits. I was hoping to do this. I’m taking out my $match and most of my $project code to avoid spoil.

db.movies.aggregate([
  {$match: {...}},
  {$group:{_id:...,
    $trunc:[min_rating:{$min:"$imdb.rating"},4]
}}
])

thanks

Hi @Delphine_Courvoisier :wave:,
Seems like you have made a syntax mistake in your pipeline.
If you want to truncate the results to the 4th digit in a $group stage, use the following:

{ $group: { _id: ..., truncatedMin: { $min: { $trunc: [ "$imdb.rating", 4 ] } } } }

But I would suggest you to use $trunc inside the $project / $addFields stage after grouping unless you specifically want the values to be truncated while grouping, therefore your pipeline should look something like this:

[
  { $group: { _id: ..., minRating: { $min: { "$imdb.rating" } } } },
  { $project: { ...., truncatedMinRating: { $trunc: [ "$minRating", 4 ] } } }
]

If you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
MongoDB

Hi @SourabhBagrecha,

your second solution (within $project) works fine whereas the first one gives an error (“A pipeline stage specification object must contain exactly one field.”).

much appreciated,
delphine

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.