How can I fetch the size of array in mongodb using springboot?

I’m new to springboot and mongodb as well. I have the following json document in mongodb

Note: Name of database is Friends and name of collection is Friend. It has many document around 118k. One sample of document is given below. –

      "address": [

Now as you can see there is Main_array inside which there is an Object inside which we have address which is an array.

Now, I want to fetch the size of this address array.

I tried this but it didn’t worked.

Note: I have to use MongoClient.

MongoDatabase database = mongoClient.getDatabase("Friends");
        MongoCollection<Document> collection = database.getCollection("Friend");

        BasicDBObject filter = new BasicDBObject("", new BasicDBObject("$exists", "true"));
        collection.find(filter).forEach((Consumer<Document>) doc -> { 
                                Object obj = doc.get("")

But I got null value in obj. Can someone please suggest me

Hi @Vartika_Malguri
Welcome to the community forum!!

I tried to reproduce the issue on my local setup with MongoDB version 5.0.7
Using the data you posted, the following query proved to be useful in finding the size of the address array.


{ "_id" : "abhj", "id" : "abhj", "Main_array" : { "number" : 12345, "pincode" : 247800, "address" : [ "vasant", "vihar", "kota" ], "address_size" : 3 } }

MongoDB Compass provides the feature to export aggregation pipeline to specific language. Please refer to the documentation export-pipeline-to-language

Below is the Java code for the above aggregation query.

 * Requires the MongoDB Java Driver.

MongoClient mongoClient = new MongoClient(
    new MongoClientURI(
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("example");

FindIterable<Document> result = collection.aggregate(Arrays.asList(new Document("$unwind", 
    new Document("path", "$Main_array")), 
    new Document("$addFields", 
    new Document("Main_array.address_size", 
    new Document("$size", "$Main_array.address")))));

Please note that if the Main_array contains more elements in the array, the above aggregation would need a projection stage in the pipeline to suit your specific need.

Let us know if you have any further questions