2

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 around 118k documents.

One sample document:

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

There is Main_array inside which there is an object inside which we have address which is an array.

I want to fetch the size of this address array.

I tried this but it didn't work.

Note: I have to use MongoClient.

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

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

But I got null value in obj.

2
  • Its better if you post your sample data in json format and post your expected output Commented May 19, 2022 at 9:06
  • Done bro. Just want to fetch the size of the "address" array Commented May 19, 2022 at 9:20

1 Answer 1

1

You can use following aggregation to find out the size.

here is the code

db.collection.aggregate([
  {
    $addFields: {
      Main_array: {
        "$map": {
          "input": "$Main_array",
          "in": {
            number: "$$this.number",
            pincode: "$$this.pincode",
            addressSize: {
              $size: "$$this.address"
            }
          }
        }
      }
    }
  }
])

Working Mongo playground

There is a TRICK to convert aggregations... The java code might be

@Autowired
private MongoTemplate mongoTemplate;

public List<YOUR_CONVERTER_CLASS> test() {

    Aggregation aggregation = Aggregation.newAggregation(
        l-> new Document("$addFields",
                new Document("Main_array",
                    new Document("$map",
                        new Document("input","$Main_array")
                        .append("in",
                            new Document("number","$$this.number")
                            .append("pincode","$$this.pincode")
                            .append("addressSize",
                                new Document("$size","$$this.address")
                            )
                        )
                    )
                )
        )
    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION_CLASS.class), YOUR_CONVERTER_CLASS.class).getMappedResults();

}
Sign up to request clarification or add additional context in comments.

5 Comments

This really seems to be promising. Thank you soo much for answering. But just want to tell the colletion is actually a private collection for which I haven't created a class and even I was asked not create class for the collection. Is there any chance we can use MongoCursor or any other method by which we do not have to create a class of the collection
and I guess we are creating Document and appending ...there are 118k documents. I guess it will be soo much work.
Hello @varman .I will be highly grateful to you if you can suggest something. Those array with size less than 3 for those I need to perform a java function as well. Do you know anything which I can use ?
You may edit this question or may open another question and show me what you need, (sample data and expected output)
Okay sure means a lot to me. I have already created the question -- stackoverflow.com/questions/72364406/…

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.