1

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.

1 Answer 1

1

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)
       )
)
Sign up to request clarification or add additional context in comments.

11 Comments

Hey thanks this looks promising I do remember this works in mongodb ...but it's giving error at Arrays<DBObject>. Have I missed something? Do we need to import something? It's giving unexpected token, Expression expected, Cannot resolve DBObject.
You can use BasicDBObject in place of DBObject
Now it's showing Expression expected, ')' expected, ;expected at Arrays<BasicDBObject>
Please add one extra ) at the end. Updating the answer
Okay ..sure man understood Thanks for helping And sorry for the inconvenience caused. I really appreciate you for helping me. I will try to edit the question again and will mark your answer as correct. Thanks
|

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.