I need to know the equivalent code in spring data mongo db to the code below:-
db.inventory.find( {
qty: { $all: [
{ "$elemMatch" : { size: "M", num: { $gt: 50} } },
{ "$elemMatch" : { num : 100, color: "green" } }
] }
} )
Documents Query One of the more common ways to query MongoDB with Spring Data is by making use of the Query and Criteria classes – which very closely mirror native operators. 2.1. Is This is simply a criterion using equality – let's see how it works.
The elemmatch query operator allows us to match documents with an array field that contains at least one element that matches the specified query criteria. As a rule of thumb, MongoDB doesn’t allow you to use the $where operator and the $text operator with the elemmatch query operator.
If we can't represent a query with the help of a method name, or criteria, we can do something more low level – use the @Query annotation. With this annotation, we can specify a raw query – as a Mongo JSON query string. 4.1.
A more flexible and powerful type of query is the regex. This c reates a criterion using a MongoDB $regex that returns all records suitable for this regexp for this field. It works similar to startingWith, endingWith operations – let's look at an example. We're now looking for all users that have names starting with A.
I am able to get the answer. This can be done in Spring data mongodb using following code
Query query = new Query();
query.addCriteria(Criteria.where("qty").elemMatch(Criteria.where("size").is("M").and("num").gt(50).elemMatch(Criteria.where("num").is(100).and("color").is("green"))));
Just to make @Vaibhav answer a bit more clearer.
given Document in DB
{
"modified": true,
"items": [
{
"modified": true,
"created": false
},
{
"modified": false,
"created": false
},
{
"modified": true,
"created": true
}
]
}
You could do following Query if you need items where both attribute of an item are true.
Query query = new Query();
query.addCriteria(Criteria.where("modified").is(true));
query.addCriteria(Criteria.where("items")
.elemMatch(Criteria.where("modified").is(true)
.and("created").is(true)));
here an example how to query with OR in elemMatch
Query query = new Query();
query.addCriteria(Criteria.where("modified").is(true));
query.addCriteria(Criteria.where("items")
.elemMatch(new Criteria().orOperator(
Criteria.where("modified").is(true),
Criteria.where("created").is(true))));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With