Home > Software design >  How can we query array field with size less than some specific value in mongodb using springboot?
How can we query array field with size less than some specific value in mongodb using springboot?

Time:05-24

My objective is to query the array fields who have size less than 5.

I tried the below solution

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

        BasicDBObject filter = new BasicDBObject("MainArray", new BasicDBObject("$lt", new BasicDBObject("$size", 4)));
        collection.find(filter).forEach((Consumer<Document>) doc -> {
//perform operations
}

I want to fetch the fields whose size is less than 4.

If I directly put the size 4 -- new BasicDBObject("$size",4) It did works.

But I want to fetch the fields with array size less than 4 In that case it didn't work.

Please provide your valuable suggestions.

CodePudding user response:

You are not using annotations.

{$expr:{$lt:[{$size:"$MainArray"}, 5]}}

You need to use $expr to use operators in simple find.

Equivalent in BasicDBObject is

new BasicDBObject("$expr", 
       new BasicDBObject("$lt", 
            Arrays<DBObject>.asList(new BasicDBObject("$size", "$MainArray"), 5)
       )
)
  • Related