SnowyCoder SnowyCoder - 2 months ago 8
Java Question

java mongodb - get array length without downloading all data

I'm using mongodb to store data for my java program and I have a collection with an array field that has a lot of things in it but i want only to get the length, without all the other data.

Now i'm using this to get it:

((UUID[])document.get("customers")).length


How can I make this not to download all the array?

A possible answer is to create an int that counts the pushes and the pulls of the array but it's not the cleanest method.

Answer

You are looking for aggregation framework where you can use the $size operator in your pipeline, this counts and returns the total the number of items in an array:

db.collection.aggregate([
    {
        "$project": {
            "_id": 0, "customer_count": { "$size": "$customers" }
         }
    }
]);

where the Java equivalent:

DBObject projectFields = new BasicDBObject("_id", 0);
projectFields.put("customer_count", new BasicDBObject( "$size", "$customers" ));
DBObject project = new BasicDBObject("$project", projectFields);

AggregationOutput output = db.getCollection("collectionName").aggregate(project);

System.out.println("\n" + output);