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. –

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

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("I_StationOverlayId_primary.0.space", new BasicDBObject("$exists", "true"));
        collection.find(filter).forEach((Consumer<Document>) doc -> { 
                                Object obj = doc.get("I_StationOverlayId_primary.0.space")
}

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.

db.example.aggregate([
  {$unwind:'$Main_array'},
  {$addFields:{'Main_array.address_size':{$size:'$Main_array.address'}}}
])

{ "_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.
 * https://mongodb.github.io/mongo-java-driver
 */

MongoClient mongoClient = new MongoClient(
    new MongoClientURI(
        "mongodb://localhost:27018/"
    )
);
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

Thanks
Aasawari