1

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.

2 Answers 2

3

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

Comments

0

You can use MongoDB's Aggregation Framework to get the size of the array. For example, given the following document structure:

> db.macross.findOne()
{
    "_id" : "SDF1",
    "crew" : [
            "Rick",
            "Minmay",
            "Roy",
            "Max",
            "Misa",
            "Milia"
    ]
}

get the size of the array

> db.macross.aggregate( 
    { $match: { _id: "SDF1" } }, 
    { $unwind: "$crew" }, 
    { $group: { _id: "", count: { $sum: 1 } } }, 
    { $project: { _id: 0, count: 1 } }
)
{ "count" : 6 }

More detailed and interesting examples are available in the docs.

1 Comment

Hey @blimpyacht what if the values in _id is dynamic. I actually have to find the size of nested array but there are around 120k documents in my collection and for each collection I have to perform this action. Can you please help me by giving suggestions

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.