Spring data mongo use OR in Query - java

Let´s see if somebody can help with this.
I want use Repository of Spring Data mongodb, and I want use Query annotation to filter the find by value A=10 or A=20
#Query("{A: 10, A:20}")
findById(int id);
Obiously "," try to make an AND, and I need an OR.
Any idea please?

Or if you are using a Criteria API
Criteria criteria = new Criteria();
criteria.orOperator(Criteria.where("A").is(10),Criteria.where("B").is(20));
Query query = new Query(criteria);
mongoOps.find(query, <Yourclass>.class, "collectionName");

I think this might work
#Query("{'$or':[ {'A':10}, {'B':20} ] }")

You can use Spring Data MongoDB like this:
Query query = new Query();
query.addCriteria(
Criteria.where("").orOperator(
Criteria.where("A").is(10),
Criteria.where("B").is(20)
)
);
mongoTemplate.find(query, YourClazz.class, "CollectionName");

In addition to helloJava answer, If you already have query with other criteria's you can add orOperation directly on query.addCriteria as below.
query.addCriteria(new Criteria().orOperator(Criteria.where("fieldA").is(value),
Criteria.where("fieldB").is(value2)));

You can use the $in operator in Spring Java:
Criteria criteria = Criteria.where("field").in(listOfOptions);

You can use the $in operator for that. I don't know Java Spring, but given your example, the Query part should look like:
#Query("{A: {$in: [10, 20]}}")

Use Spring's BasicQuery:
DBObject queryCondition = new BasicDBObject();
BasicDBList values = new BasicDBList();
values.add(new BasicDBObject("A", 10));
values.add(new BasicDBObject("B", 20));
queryCondition.put("$or", values);
Query query = new BasicQuery(queryCondition);
mongoTemplate.find(query, clazz);

Query query = new Query();
Criteria criteria = new Criteria();
criteria.orOperator(Criteria.where("category").is("your_Value_Category"),
Criteria.where("parentCategory").is("your_Value_ParentCategory"));
query.addCriteria(criteria);
mongoTemplate.find(query, YourPersistenceClass.class);

You can use Spring's Query structure:
Query query = new Query();
query.addCriteria(Criteria.where("id").is(10).orOperator(Criteria.where("id").is(20));
this.client.findOne(query, clazz);

Related

How to perform aggregation in mongodb using Java by setting query object instead of matchoperation?

Below is the code:
Criteria criteria=null;
criteria = new Criteria().andOperator(Criteria.where("OwnerId").is(ownerId), Criteria.where("Environment").is(env), Criteria.where("ServiceName").in(api));
MatchOperation matchOp= Aggregation.match(criteria);
ProjectionOperation projOp= Aggregation.project("SubServices").andInclude("ServerGroupName").andInclude("NodeName").andInclude("ServiceVersion")
.andExclude("_id");
Aggregation aggr = Aggregation.newAggregation(matchOp, projOp);
AggregationResults<Document> aggregate = mongoOperations.aggregate(aggr, "CNF_SERVICE",Document.class,"config",env);
The above code works fine. However, I need to make below changes in order to generate criteria dynamically:
Criteria criteria=new Criteria();
Query query= new Query();
if(ownerId!=null && ownerId>0) {
query.addCriteria(criteria.andOperator(Criteria.where("OwnerId").is(ownerId)));
}
if(env!=null) {
query.addCriteria(criteria.andOperator(Criteria.where("Environment").is(env)));
}
if(api!=null) {
query.addCriteria(criteria.andOperator(Criteria.where("ServiceName").in(api)));
}
MatchOperation matchOp= Aggregation.match("How to set the query here?");
ProjectionOperation projOp= Aggregation.project("SubServices").andInclude("ServerGroupName").andInclude("NodeName").andInclude("ServiceVersion")
.andExclude("_id");
Aggregation aggr = Aggregation.newAggregation(matchOp, projOp);
AggregationResults<Document> aggregate = mongoOperations.aggregate(aggr, "CNF_SERVICE",Document.class,"config",env);
I need to set the query to criteria and apply it to the match operation. How to achieve this?
Instead of Match Operation you can achieve like below code:
Hope, it will helpful
Criteria criteria=new Criteria();
Query query= new Query(); query.addCriteria(criteria.andOperator(Criteria.where("OwnerId").is(ownerId))); query.fields().include("SubServices"); query.fields().include("ServerGroupName"); query.fields().exclude("_id");
MongoTemplate.find(query, Map.Class, collectionName);

Mongo $or query inside $and using Java MongoOperations [duplicate]

Let´s see if somebody can help with this.
I want use Repository of Spring Data mongodb, and I want use Query annotation to filter the find by value A=10 or A=20
#Query("{A: 10, A:20}")
findById(int id);
Obiously "," try to make an AND, and I need an OR.
Any idea please?
Or if you are using a Criteria API
Criteria criteria = new Criteria();
criteria.orOperator(Criteria.where("A").is(10),Criteria.where("B").is(20));
Query query = new Query(criteria);
mongoOps.find(query, <Yourclass>.class, "collectionName");
I think this might work
#Query("{'$or':[ {'A':10}, {'B':20} ] }")
You can use Spring Data MongoDB like this:
Query query = new Query();
query.addCriteria(
Criteria.where("").orOperator(
Criteria.where("A").is(10),
Criteria.where("B").is(20)
)
);
mongoTemplate.find(query, YourClazz.class, "CollectionName");
In addition to helloJava answer, If you already have query with other criteria's you can add orOperation directly on query.addCriteria as below.
query.addCriteria(new Criteria().orOperator(Criteria.where("fieldA").is(value),
Criteria.where("fieldB").is(value2)));
You can use the $in operator in Spring Java:
Criteria criteria = Criteria.where("field").in(listOfOptions);
You can use the $in operator for that. I don't know Java Spring, but given your example, the Query part should look like:
#Query("{A: {$in: [10, 20]}}")
Use Spring's BasicQuery:
DBObject queryCondition = new BasicDBObject();
BasicDBList values = new BasicDBList();
values.add(new BasicDBObject("A", 10));
values.add(new BasicDBObject("B", 20));
queryCondition.put("$or", values);
Query query = new BasicQuery(queryCondition);
mongoTemplate.find(query, clazz);
Query query = new Query();
Criteria criteria = new Criteria();
criteria.orOperator(Criteria.where("category").is("your_Value_Category"),
Criteria.where("parentCategory").is("your_Value_ParentCategory"));
query.addCriteria(criteria);
mongoTemplate.find(query, YourPersistenceClass.class);
You can use Spring's Query structure:
Query query = new Query();
query.addCriteria(Criteria.where("id").is(10).orOperator(Criteria.where("id").is(20));
this.client.findOne(query, clazz);

How to query mongo db by _id?

I am using MongoDB with Spring. I want to query the database by _id.
Currently I have this query:
Query q = new Query(Criteria.where("_id").is(someId).and("deleted").is(false));
But this is giving me StackOverflowError somehow. What's wrong with this query? Or what is a better way of doing this?
Create an explicit AND query instead of a chained one using the $and operator Criteria.andOperator() for all of the provided criteria as follows:
Query q = new Query(
new Criteria().andOperator(
Criteria.where("_id").is(someId),
Criteria.where("deleted").is("false")
)
);
This is normally used in instances where you can't use Criteria.and() to add multiple criteria into the same field, for example
Query q = new Query();
q.addCriteria(Criteria.where("age").lt(40).and("age").gt(10));
will throw an error, so a workaround would be to use Criteria.andOperator() as
Query q = new Query();
q.addCriteria(
Criteria.where("age").exists(true).andOperator(
Criteria.where("age").gt(10),
Criteria.where("age").lt(40)
)
);

Java MongoDB search for value in multiple fields

i have a java method
public List<Project> tagSearch(String searchCriteria){
Query query = new Query();
return mongoTemplate.find(query.addCriteria(Criteria.where("projectTag")
.regex(searchCriteria,"i")), Project.class, COLLECTION_NAME);
}
here it is searching the searchCriteria value in the field projectTag. I want to search for that value in multiple fields. for example another field projectName
appreciate your assistance.
Use orOperator
You can use as many criteria in orOperator. Then it will look like this :
Query query = new Query();
Criteria criteria1 = new Criteria().where("projectTag").regex(searchCriteria, "i");
Criteria criteria2 = new Criteria().where("projectName").regex(searchCriteria, "i");
query.addCriteria(new Criteria().orOperator(c1,c2));
return mongoTemplate.find(query, Project.class, COLLECTION_NAME);
You can use below code
final Criteria criteria = new Criteria();
criteria.orOperator(Criteria.where("projectTag").regex(searchCriteria, "i"),
Criteria.where("projectName").regex(searchCriteria, "i"));
final Query query = new Query(criteria);
final List<Project> projectEntities = mongoTemplate.find(query, Project.class);

Spring Data MongoDB Date Between

I use spring data mongodb.
I want the records between two dates. The following MongoDB Query works:
db.posts.find({startDate: {$gte: start, $lt: end}});
My attempted Spring data query object code translation does not work:
Query query = new Query();
query.addCriteria(Criteria.where("startDate").gte(startDate)
.and("startDate").lt(endDate));
What is the correct order of method calls to build the Mongo query I need?
Do not include the 'and("startDate")' part in your criteria.
Instead of :
query.addCriteria(Criteria.where("startDate").gte(startDate).and("startDate").lt(endDate));
You should use:
query.addCriteria(Criteria.where("startDate").gte(startDate).lt(endDate));
When you include the 'and("startDate")' part, Mongo see's it as two different entries on the same property.
You also can add query annotaion:
#Query("{'date' : { $gte: ?0, $lte: ?1 } }")
public List<AnyYourObj> getObjectByDate(Date from, Date to);
Or proper spring data method signature:
public List<AnyYourObj> findByDateBetween(Date from, Date to);
Both of these approaches give the same result.
You can read more here https://www.baeldung.com/queries-in-spring-data-mongodb
and here https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/
Reference here
Query query = new Query(
Criteria.where("ip").is(ip)
.andOperator(
Criteria.where("createdDate").lt(endDate),
Criteria.where("createdDate").gte(startDate)
)
);
I had to find dates between on field publishedDate and here is how I did it:
Criteria publishedDateCriteria = Criteria
.where("publishedDateObject").gte(psDate)
.lte(peDate);
Query query = new Query(publishedDateCriteria);
mongoTemplate.find(query,
MyDocumentObject.class));
I did like this
public interface PolicyRepository extends MongoRepository<Policy, String> {
#Query("{'lastDate':{$gt:?0,$lt:?1}}")
public List<Policy> findAllPolicies(Date today,Date somedate);
}
This works on version 2.7.2 of the Java driver
DBCollection coll = db.getCollection("posts");
BasicDBObject date = new BasicDBObject();
date.append("$gte", new Date(startDate));
date.append("$lte", new Date(endDate));
DBObject query = new BasicDBObject();
query.put("date", date);
DBCursor cursor = coll.find(query);
Also, for the record you have "startDate" for both the gte and the lte parameters.
It works, he is some sample code:
Criteria criteria = Criteria.where("pt").gte(startDate)
.andOperator(Criteria.where("pt").lt(endDate));
public interface MyRepository extends MongoRepository<MyObject, MyObjectId> {
List<MyObject> findByMydatefieldBetween(DateTime startDate, DateTime endDate);
}
https://docs.spring.io/spring-data/mongodb/docs/2.2.x-SNAPSHOT/reference/html/#mongodb.repositories.queries
if (metaData.getToValue() == null){
dynamicCriteria = Criteria.where("metaData.key").is(metaData.getKey()).andOperator(Criteria.where("metaData.value").is(metaData.getFromValue()));
}else {
dynamicCriteria = Criteria.where("metaData.key").is(metaData.getKey()).orOperator(Criteria.where("metaData.value").gte(metaData.getFromValue()).lt(metaData.getToValue()));
}
Use MongoRepository Query method like this:
List<T> findByStartDateBetween(Range<Integer> dataRange);
use Range for detail range settings.
simliar question
Can you try this below query. This should work for your case.
Query query = new Query(
Criteria.andOperator(
Criteria.where("startDate").gte(startDate),
Criteria.where("startDate").lt(endDate)
)
);
Search By Date Column in spring boot mongo db using criteria(Complex Query)[Search by date column in spring boot mongodb using criteria][1]

Categories