MongoDB how to count array elements with Java driver

aSlug

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.

s7vr

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));

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to count certain elements in array?

How to count array elements properly with multiple aggregation in Spring Data MongoDB?

How do you count the elements of an array in java

Updating an array in MongoDB using Java driver

how to count duplicate elements in array in java

MongoDB: Count of matching array elements

How to match a document with existing array elements in mongodb using java driver

How to maintain the top count(s) of array elements in mongoDB?

How to update array elements in mongodb

Count how many elements in array

How to Count Matched array elements

How to count matched elements from an Array in another Array MongoDB

How to print the count of array elements along with another variable in MongoDB

How to count objects in an array in mongodb?

Make an Array of unique elements in c# mongodb driver

MongoDB count documents for each array elements

how to count/sum array on mongodb?

How to filter elements of array in mongodb

How to count array duplicate elements in MongoDB

How to count array elements in mongo

How to query mongodb with java driver

Count results with MongoDB 3.0 Java Driver

How to retrieve / find all elements of a nested array in MongoDB Java

MongoDB - How do group on date and count elements in array

MongoDB: How to count elements in array which is inside of two objects?

How to access array elements in mongodb

MongoDB how to update a count field with the number of elements that are in an array on the document

MongoDB: count of array elements in whole collection

How to count the elements in an Array in Ruby