3

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.

2 Answers 2

5

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));
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a new field and put the size of the array inside it and use it for count or sorting.

use "addFields" java Helper

addFields(new Field("productsCount",
            new Document("$size", "$products")));

Where

  1. 'productsCount' is the name of the new field
  2. 'products' is the Array
  3. '$size' is the MongoDB aggregation.

1 Comment

Then you have to maintain this field. Saving calculations is almost never a good idea. (Notable exception being long calculations) It's better to calculate in memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.