I have a tricky situation to find the items in mongoDB based on datetime range.
Condition: given time is in between datetime field and datetime + 12 hours
Example:
Given time:
datetime: "2022-07-18T10:00:00"
Mongo data:
{
"id": "AC-8632-2022-07-18",
"version": "1658144238",
"departure": "2022-07-18T08:00:00"
}
I want to fetch the data based on the condition :
"2022-07-18T08:00:00" < "2022-07-18T10:00:00" < "2022-07-18T20:00:00"
Query like:
Bson query = Filters.and(
Filters.gt("departure", datetime),
Filters.lt("departure" + 12, datetime));
Any suggestions on achieving below would be helpful.
Related
I am using Java to run queries on ElasticSearch. I'm having difficulties running range queries using boolQuery() API and queryStringQuery as input. here's the code:
QueryBuilder stringQuery = QueryBuilders.queryStringQuery(query);
QueryBuilder finalQuery = QueryBuilders.boolQuery().should(stringQuery);
The data field for date has the following format:
"startedOn" : { "type" : "date", "format": "yyyy-MM-dd HH:mm:ss.SSSSSS" }
and I am using queries like these:
StartedOn < 2020-06-29
StartedOn : [2020-06-20 TO 2020-06-25]
But none of them seem to return the correct results. Am I missing something here?
Thanks.
I want to search in DB all rows with a part of Timestamp like "2014-08-12". And if there are rows like "2014-08-12 16:58:48.477" or "2014-08-12 15:58:48.477" I want to get it
I use JPA + Hibernate + Criteria API
document.setRegister_date(DateUtil.DateToSQLTimestamp("2013-08-12 16:58:48.477"));
if (register_date != null) {
predicates.add(cb.equal(DocumentsRoot.get("register_date"), register_date));
}
If you know that the format will always exclude time, you can use a range query where you can set the from as 00:00:00.001 and to as 23:59:59.999
String date = "2013-08-12";
document.setRegister_date(DateUtil.DateToSQLTimestamp(date + " 00:00:00.000"));
document.setRegister_end_date(DateUtil.DateToSQLTimestamp(date + " 23:59:59.999"));
Timestamp register_date = document.getRegister_date();
Timestamp register_end_date = document.getRegister_end_date();
predicates.add(cb.between(DocumentsRoot.get("register_date"), register_date, register_end_date));
I already can execute the desired query on mongoshell, but i need to make the same query using Java and MongoOperations.
I have checked this question, which is very similar, but it only has one condition, as mine has two and uses the $gte and $lt operators. Here's the working mongo Query:
db.getCollection('example').update({"idVar": "desiredValued"}, { $pull: { "listaHoras": { $gte: ISODate("2016-11-06T05:50:00.000Z"), $lt: ISODate("2016-11-06T06:30:00.000Z")}}})
Sample doc:
"_id" : ObjectId("58221b4610a3c71f1894ce75"),
"idVar" : "56b11259272f5515b05d70bc",
"date" : ISODate("2016-11-06T03:00:00.000Z"),
"listaHoras" : [
ISODate("2016-11-06T05:40:00.000Z"),
ISODate("2016-11-06T06:30:00.000Z"),
ISODate("2016-11-06T06:40:00.000Z")
]
Where i'll have the ISODATE as a Date variable in Java, and the desiredValue as a String variable.
So far, i have i did the following, using the previously mentioned question as example:
BasicDBObject match = new BasicDBObject("idVar", desiredValue); // to match your document
BasicDBObject update = new BasicDBObject("listaHoras", new BasicDBObject("itemID", "1"));
coll.update(match, new BasicDBObject("$pull", update));
But, as you can see, this is NOT equivalent to the desired query. Since the match for the $pull is matching "itemID"with "1". I do not know, nor was i able to find how to properly use the $gte and $lt on the same query. Neither on how to use just one or both of them. I know it CAN be done as seen on the MongoOperatioons API which says:
"update - the update document that contains the updated object or $ operators to manipulate the existing object."
Anyone knows how it can be done? And if the Date type in Java matches the ISODATE on the Mongo?
I managed to find a solution. It is similar to what Veeram posted as a answer but it's slightly different. I simply removed his updateCriteria and used a BasicDBObject in it's place.
Here's how the full code looks:
Query findQuery = new Query();
Criteria findCriteria = Criteria.where("idVar").is(idVar);
findQuery.addCriteria(findCriteria);
Update update = new Update().pull("listaHoras", new BasicDBObject( "$gte", start).append("$lte", end));
mongoOps.updateMulti(findQuery, update, "CollectionName");
Where start and end are Date variables recieved by the method. Also important to note that Mongo uses the UTC as default timezone, so we must properly format the time in order for it to remove the desired values.
You can try something like below. This will remove the two items from the listaHoras array.
Query findQuery = new Query();
Criteria findCriteria =
Criteria.where("idVar").is("56b11259272f5515b05d70bc");
findQuery.addCriteria(findCriteria);
LocalDate startDt = LocalDate.of(2016, 11, 6);
LocalTime startTm = LocalTime.of(5, 40, 0);
LocalDate endDt = LocalDate.of(2016, 11, 6);
LocalTime endTm = LocalTime.of(6, 35, 0);
Date start = Date.from(LocalDateTime.of(startDt, startTm).toInstant(ZoneOffset.UTC));
Date end = Date.from(LocalDateTime.of(endDt, endTm).toInstant(ZoneOffset.UTC));
Query updateQuery = new Query();
Criteria updateCriteria =
Criteria.where(null).gte(start).lt(end);
updateQuery.addCriteria(updateCriteria);
mongoOperations.updateMulti(findQuery, update, "example");
I have one store which is getting date in dd-MM-yyyy format. I want to sort this date in my ExtJS grid in such way that all the date of same month should display one after the other and next other month date should be displayed. But what is happening is that in ExtJS all the dates are treated as string, so I am getting output as 01-01-2015 next date is 01-02-2015 which I don't want. So is it possible for custom sorting in ExtJS 3.2`?
Code snippet:
var memebersListStore = new Ext.data.JsonStore({
name: 'approverlist',
autoLoad: true,
url: 'json/loginLogout.do?Uid=' + userLdapId + '&startDate=' + selectedStartDate + '&endDate=' + selectedEndDate,
fields: ['weekDate'],
sortInfo: {
field: 'weekDate',
direction: 'ASC'
},
listeners: {
load: function (store, records, options) {
if (store.getTotalCount() === 0) {
memebersListStoreGrid.reconfigure(store, columnsTwo);
} else {
memebersListStoreGrid.reconfigure(store, columnsOne);
}
}
}
});
Anybody has any idea?
in fields you have to define type. like this
fields: [{name: 'weekDate', type: 'DATE'}]
Im trying to do a query to get all the values from my DB wich each have a date. One example:
leadTime: [
{
date: ISODate("2014-03-19T23:00:00Z"),
value: 25.8
},
{
date: ISODate("2014-03-20T23:00:00Z"),
value: 31.299999999999997
},
{
date: ISODate("2014-03-21T23:00:00Z"),
value: 34.4
}
]
enter code here
My code is:
DBObject query=new BasicDBObject("group",group);
DBObject serieData= col.findOne(query,new BasicDBObject(serie, 1));
if (serieData != null) {
List<DBObject> data = (List<DBObject>) serieData.get(serie);
for (DBObject item : data) {
result.add(new HistoryData((Date) item.get("date"),(Double) item.get("value")));
}
Now I want to get the values that the date is bigger than a date that I pass by parameter. The query I did is this:
DBObject query=new BasicDBObject("group",group)
.append("date", new BasicDBObject("$gte", parameterDate))
;
But I always receive the result empty, can you help me? sorry for my english and than
Assuming that leadTime is a field in your documents, your query has to look like this
DBObject query=new BasicDBObject("group",group)
.append("leadTime.date", new BasicDBObject("$gte", parameterDate))
;
The way you did it, MongoDB would have searched for a date field in your document root:
{ _id: "Foo",
date: ISODate("2014-03-19T23:00:00Z"),
[...]
}
Queries in MongoDB don't make a difference if the queried field is a single value or an array, so using the dot notation on a field which holds an array of subdocuments is perfectly valid.
What you want to do is not possible with a simple query.
But if you still want to do it in mongodb you need to use the aggregation framework, with something like that :
db.<col_name>.aggregate( [ { $unwind : "$group" }, { $match : {'group.date': { $gte : parameterDate } } ] )
this a js command, but you should be able to translate it easly in Java Driver (you can also add a $project operation to just return needed fields).