MongoDB how to count array elements with Java driver

Tags: , ,



I need my application to count the size of an array foos inside a document using Java driver 3.8. I know I can do this with the shell

db.collection.aggregate(
   [
      {
         $match: { _id: 123456789 }
      },
      {
         $project: {
            count: { $size: "$foos" }
         }
      }
   ]
)

but I have no idea of how to do this with java, because the only method producing a $size operator I found is Filters.size(String fieldName, int size) that is meant to look for documents where array fieldName has size size. I searched inside com.mongodb.client.model package but I found nothing to answer my question.

Answer

No there are no helpers in java driver to help with aggregation expression for $project stage.

Try

Bson match = new Document("$match", Filters.eq("_id", 123456789 ));
Bson projection = new Document("$size", "$foos" );
Bson project = Aggregates.project(new Document("count", projection) );
collection.aggregate(Arrays.asList(match, project));


Source: stackoverflow