1

I actually want to fetch the fields of document in mongodb where the size of a nested array is less than 4. Providing the mongo document in json format --

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

Now here the nested array is address. I want to fetch the doc whose address array has a size less than 4.

Also I'm restricted to use MongoClient and BasicDBObject[can't use mongoRepo or mongoTemplete] I tried the below code --

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

        BasicDBObject filter = new BasicDBObject("Main_Array.address", new BasicDBObject("$lt", new BasicDBObject("$size", 4)));
        collection.find(filter).forEach((Consumer<Document>) doc -> {
//some java functions
}

I actually created a question earlier -- How can we query array field with size less than some specific value in mongodb using springboot?

But I was suggested by the person who answered it. That I should created a new question as I dind't mentioned that I'm willing to look at a nested array and as a result the mongo query is going to change.

2
  • 1
    It is not going to be simple find. You need to use aggregation framework. Either unwind and size or sum and map. Commented May 24, 2022 at 14:31
  • Okay .. I'm new to this that's why I'm not aware about all these ...Do you have nay idea which will be best if there are around120k documents in the collection. Because for aggregation I was looking over the internet they were suggesting to first create a converter class -- and then copy the data in that class and then use aggregation which will not be optimized solution. Do you have idea which will be optimized for such larger amount of documents Commented May 25, 2022 at 10:06

0

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.