Mongo aggregation $bsonSize unrecognized

Hello everyone, I try to represent next mongo query

db.products.aggregate([
  {
    $project: {
      "resulted_size": { $sum: { $bsonSize: "$$ROOT" } }
    }
  }
])

in my Scala code, I use mongo-java-driver and when I try to use MQL I see the next error ‘Unrecognized expression $bsonSize’

Code:

collection.
  aggregate(
    Seq(
      Aggregates.group(
        null,
        Accumulators.sum("resulted_size", BsonDocument("$bsonSize" -> BsonString("$$ROOT")))
      )
    )
  )

How can I need to represent this aggregation in my code?

@devsol_pwn3d, the $bsonSize operator was introduced in MongoDB 4.4.

If you’re connecting to a MongoDB 4.2 or older cluster the operator would not be available.

1 Like

Thank you, yes the version is 4.2.18(

Note that you cannot use $sum this way in $project - used a a regular expression it expects an array (to sum its elements). The only time you can give it a number rather than an array of numbers is when you are using it as an accumulator in $group.

Asya

I see you’re using group in your Scala code, so it’s just your shell aggregate that’s using the wrong stage name most likely.