MongoDB ISODate parse with Spring Data - java

I am using MongoDB 3 and I'm trying to get all purchases by day. The problem is that I have the following value in mongo:
"createDate" : ISODate("2016-04-11T17:57:12.960Z")
And I want to get all the purchases using the following date format dd/MM/yyyy. This is my method:
public List<Purchase> getPurchasesByDate(BigInteger company, Date date, PurchaseStatus status) {
Query query = new Query();
query.addCriteria(Criteria.where("createDate").lte(date).and("status").is(status.toString()).and("company").is(company.toString()));
return mongoTemplate.find(query, Purchase.class);
}
This is what I seeing into mongo console:
{ "createDate" : { "$lte" : { "$date" : "2016-04-11T19:14:56.322Z"} } , "status" : "PAYED" , "company" : "1"}
Obviously is not returning any values. I'm calling my method like this getPurchasesByDate(1, new Date(), PurchaseStatus.PAYED).
Does anybody knows how can I can get all documents by date using this format dd/MM/yyyy?
thanks

Related

Spring Data Mongo: criteria doesn't filter by Date

I need to filter my data from mongo db collection by date.
I created following query for complete this task:
new Criteria(Constants.MONGO_POST_CREATION_DATE).gte(DateUtil.getUTCDate(searchDTO.getStartDate())
this criteria generates following query:
{ "creationTime" : { "$gte" : { "$date" : "2018-10-28T21:00:00.000Z"} , "$lte" : { "$date" : "2019-02-06T08:29:00.000Z"}}}
But i couldn't get any data by using this query. It just returns empty result list. I've found following question on stackoverflow which explains how to write correct query for filtering by Date:
Question
So, with query from that answer i'm able to get expected result from mongo:
{ "creationTime" : { "$gte" : new Date("2019-01-24T21:00:00.000Z") , "$lte" : new Date("2019-02-06T08:29:00.000Z")}}
What do i need to change to force Criteria generate proper query for Date?

How to get the specified object fields from array in spring mongo using MongoRepository interface

Json Object
{
"_id" : ObjectId("5c07afde9bc2e9ab1dfb6c01"),
"rates" : [
{
"day" : "Mon",
"start" : "0900",
"end" : "1800",
"found " : "active"
},
{
"day" : "Tue",
"start" : "1800",
"end" : "0900",
"found " : "inactive"
},
{
"day" : "Fri",
"start" : "1800",
"end" : "0900",
"found " : "inactive"
}
]
}
I used below link to get one of the object from array:
get the specified fields from array
When I query like
myRepositroy.findByDayAndTime("Fri"));
public MyStatus findByDayAndTime(String day) {
// i get required object
Query query = new Query();
query.addCriteria(Criteria.where("rates.day").is(day));
query.fields().include("rates.$");
return mongoTemplate.find(query, MyStatus.class);
}
Calling repository to find required object from array with multiple fields
myRepositroy.findByDayAndTime("Fri","1800"));
Below is the method used for querying on multiple fields like
public MyStatus findByDayAndTime(String day,String start) {
Query query = new Query();
query.addCriteria(Criteria.where("rates.day").is(day).and("rates.start").is(start));
query.fields().include("rates.$");
return mongoTemplate.find(query, MyStatus.class);
}
but I am getting as a output 2nd index array object instead of 3rd index array object.
How do I get the only required object from array by using query with values like ("Fri","1800")
Problem into query. Just replace with this code
public MyStatus findByDayAndTime(String day,String start) {
Query query = new Query();
query.addCriteria(Criteria.where("rates").elemMatch(Criteria.where("day").is(day).and("start").is(start)));
query.fields().include("rates.$");
return mongoTemplate.find(query, MyStatus.class);
}
It's working for me. Good to have go with doc mongodb official doc
Projection Operator

Morphia query date range

What is the equivalent of the following Mongo query in Morphia?
db.events.find({ "date": { $gte: ISODate("2001-01-01") , $lt: ISODate("2001-01-02")} })
Currently I have the following code
Query<Event> query = dataStore.find(Event.class);
query.field("date").greaterThanOrEq(startDate).field("date").lessThan(endDate);
but it results in the following Mongo query
{ "$and" : [ { "date" : { "$gte" : { "$date" : "2001-01-01T00:00:00.000Z"}}} , { "date" : { "$lt" : { "$date" : "2001-01-02T00:00:00.000Z"}}}]}
I suppose the end result is the same, but the resulting query is more verbose.
Use criteria with add method
Something like
Query<Event> query = datastore.find(Event.class);
query.criteria("date").greaterThanOrEq(startDate).add(query.criteria("date").lessThan(endDate));
You need to create a query then add date range condition like followed.
Query<Event> queryForEvent = ds.createQuery(Event.class);
queryForEvent.field("date").greaterThanOrEq(startDate);
queryForEvent.field("date").lessThan(endDate);
List<Event> eventList = queryForEvent.asList();
Hoping you will find it useful.

Getting com.mongodb.MongoException$DuplicateKey in mongodb with java using upsert

I am not able to update the existing record with mongo db upsert using java.
I wrote a query to find the record using id but when trying to update its throwing com.mongodb.MongoException$DuplicateKey exception.
Sample data:
{"_id" : ObjectId("5788bef4191fda5c9077af78"),
"type" : "PRIVATE",
"users" : [
{
"_id" : "800",
"Name" : "Jack"
},
{
"_id" : "530a7998-ba3f-4366-8d21-bb1ca688cfdb",
"Name" : "Ashley"
}
]}
Java query
Query query = new Query();
query.addCriteria(Criteria.where("_id").is("5788bef4191fda5c9077af78"));
Update args = new Update();
args.addToSet("users", users);// users is a List<User>users.
args.addToSet("type", "GROUP");
mongoOps.upsert(query, args, Rooms.class, ROOMS);//mongoOps is MongoOperations
We need to pass only list to addToset . And set to update a string field.
Below code worked and document got updated.
Update args = new Update(); args.addToSet("users", new BasicDBObject("$each", users)); args.set("type", "GROUP"); mongoOps.upsert(query, args, Rooms.class, ROOMS);

Mongodb query on date has no results (java)

My mongodb query is not returning any results and I can't spot why.
Here is the relevant contents of my data:
> db.reports.find({},{endDate:1})
{ "_id" : ObjectId("5182882ae4b032c67674c494"), "endDate" : ISODate("2013-05-02T15:37:11.032Z") }
{ "_id" : ObjectId("51828859e4b032c67674c495"), "endDate" : ISODate("2013-05-02T15:37:57.749Z") }
So I have two entries with dates 2013-05-02 15:37:11-57
I want to find all entries with a date less than or equal to that latest date, but I get no results using this query:
db.reports.find({ "endDate" : { "$lte" : { "$date" : "2013-05-02T15:37:11.032Z"}}},{endDate:1})
I am generating the query in java using:
BasicDBObject oldReportSelector = (BasicDBObject) BasicDBObjectBuilder.start()
.add("endDate",
BasicDBObjectBuilder.start().add("$lte",myDate).get())
.get();
What am I doing wrong here?
Edit to add:
myDate is calculated using:
Date endDate = new Date()
Date myDate = new Date(endDate.getTime()-(interval*quantityArchivedReports));
Currently interval = 86400000 and quantityArchivedReports = 4
The reason you are not getting anything in the shell is that you are not using the date format the shell expects. Try changing your query to:
> db.reports.find({ "endDate" : { "$lte" : new Date("2013-05-02T15:37:11.032Z")}})
{ "_id" : ObjectId("5182882ae4b032c67674c494"), "endDate" : ISODate("2013-05-02T15:37:11.032Z") }
You can then use the shell to verify if your code has actually generated a correct date to get back any data or not.

Categories