Spring Data MongoDB Date Between - java

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]

Related

Spring + MongoDB - MongoTemplate + Criteria Query

I am using Spring Boot + MongoDB. I need to query database based on some criteria where my methods looks like below:
#Override
public List<MyCollection> findBuyByCriteria(Request request) {
Query search = new Query();
search.addCriteria(Criteria.where("ItmId").in(request.getItmIds()));
return mongoTemplate.find(search, MyCollection.class);
}
Problem that I am facing is:
At line
search.addCriteria(Criteria.where("ItmId").in(request.getItmIds()));
request.getItmIds has 1 million Ids due to which I am getting an exception
org.bson.BsonMaximumSizeExceededException: Document size of 46282052 is larger than maximum of 16793600
Can anyone help me with this one?
If you are using Spring Data JPA, you can do something like:
findBySomeField(String someField)
If you have a more complex query, you can actually use JPQL and write a custom query.
#Query(value = "SELECT o.* from SomeObject o WHERE :someField IS NULL OR o.someField = :somefield)
public findBySomeField(#Param("someField") String someField);

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)
)
);

Spring data mongodb query by json string

My code need to support any query that being sent by the client . The client will be sending the query as a json . I have done this using java mongo driver low level api using following code , BasicDBObject queryObject = (BasicDBObject) JSON.parse(whereJson.toString());
As i am a newbie in spring data mongodb , i am unable to find a similar solution in either Query or Criteria classes . I have checked different tutorials and couldn't find any . Is it possible to do in spring data mongodb or should i use low level apis itself ?
You can create Query instances from a plain JSON String by using BasicQuery object. The following example demonstrates how you can construct a Query instance from a plain JSON String:
BasicQuery query = new BasicQuery("{ age : { $lt : 50 } }");
List<Person> result = mongoTemplate.find(query, Person.class);
Another way which uses the low-level API:
DBObject dbObject = (DBObject) JSON.parse(query);
DBCursor cursor = mongoTemplate.getCollection("person").find(dbObject);
You can then map the return objects back to your Person POJO using the MongoConverter read() method:
List<Person> returnList = new ArrayList<Person>();
while (cursor.hasNext()) {
DBObject obj = cursor.next();
Person person = mongoTemplate.getConverter().read(Person.class, obj);
returnList.add(person);
}

Spring data mongo use OR in Query

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);

Categories