Trouble using $trunc inside of $group

Hi,

I was working on Ch3Lab1 and through testing different queries, I came up with this issue. First I have this working query:
db.movies.aggregate([ {$match: {awards: <select strings that start with 'Won '>}}, {$group: {_id: null, avg_rating: {$avg: "$imdb.rating"}}} ])

Gives a result of:
{ "_id" : null, "avg_rating" : 7.490729001584786 }

But when I try to truncate avg_rating in the following way:

db.movies.aggregate([
	{$match: {awards: <select strings that start with 'Won '>}},
	{$group: {_id: null, avg_rating: {$trunc: [{$avg: "$imdb.rating"}, 4]}}}
])

I get the following:
"errmsg" : "The $trunc accumulator is a unary operator",

Is my syntax incorrect? Checked the docs and it seems like this is the way one should go about this operation.

Thanks!

Please refer to https://docs.mongodb.com/manual/reference/operator/aggregation/trunc/.

The syntax for $trunc has changed in 4.2 and it looks like you are using the 4.2 syntax which is not available in earlier versions.

Right. The server version is indeed 3.6. Tried to adapt the syntax to pre-4.2.

{ $trunc: <number> }

db.movies.aggregate([ {$match: {awards: <select strings that start with 'Won '>}}, {$group: {_id: null, avg_rating: {$trunc: {$avg: "$imdb.rating"}}}} ])

and I get a

"errmsg" : "unknown group operator '$trunc'",

Could it be that $trunc is not available at all in v3.6.? No other way to truncate in 3.6?

Thanks!

According to https://docs.mongodb.com/manual/reference/operator/aggregation/group/ it appears that $trunc is not a valid $group operator. I would move that into a separate $project or $addFields stage.

2 Likes