spring mongodb - How to provide match condition to check for empty array using spring data mongodb api?
Asked Answered
B

2

6

how to perform below operation (it is the actual mongo query) using MatchOperation in Spring data mongodb ?

$match: { "docs": { $ne: [] } }

here docs is an array field and want to check that it is not empty.

Bertine answered 15/5, 2017 at 17:38 Comment(9)
Possible duplicate of how to search the array with no empty value from mongodb in java?Unloosen
I want to perfrom this using spring data's query criteria, not direclty on BasicDBObjectBertine
Here you go Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(Criteria.where("docs").exists(true)));Unloosen
it checks for the presence of the field (which in this case do exists) not the value of the field which is emptyBertine
Something like Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("docs").ne(Collections.EMPTY_LIST))); Unloosen
Criteria.where("docs").not().size(0);Faradism
Thanks Veeram, that worked.Bertine
I tried both options Criteria.where("docs").not().size(0) & Criteria.where("docs").ne(Collections.EMPTY_LIST) . but its not working, however if I use the same query generated on console, then I can see proper data, strange!! @Bertine can you plz tell which one you implementedReligieuse
it is too late but I did end up using Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("docs").ne(Collections.EMPTY_LIST)));Bertine
J
0

I also had a similar problem, but I solved is as below.

MatchOperation mathOpertaion = match(Criteria.where("docs") .elemMatch(new Criteria().exists(true)));

Jampan answered 26/4, 2022 at 2:4 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Bragi
E
0

You can use .not

Criteria.where("arr").not().size(0)

Exaggeration answered 23/5, 2023 at 6:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.