How can I search less than needed date with springdata and mongodb? - mongodb

Try to search by date from mongodb via springdata generated method. But I can't. What do I wrong?
I tried
#RestResource(path = "findByEndDate")
List<Event> findByEndDate(#Param("endDate") Date java.util.Date.endDate);
OR
#RestResource(path = "findByEndDate")
List<Event> findByEndDate(#DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")#Param("endDate") Date endDate);
but unsuccessfully
Data stored in database:
{
"_embedded" : {
"events" : [ {
"uuid" : "TEST_UUID_EVENT",
"testObject" : true,
"startDate" : "2016-07-29T11:23:41.815+0000",
"endDate" : "2016-07-29T23:23:41.815+0000"
...

Try this
By looking your schema the data endDate is present inside events[], so it should be queried like as follows
#RestResource(path = "findByEndDate")
List<Event> findByEndDate(#Param("events.endDate") Date java.util.Date.endDate);
This document lists on various ways of querying the mongodb thru spring data.
http://www.mkyong.com/mongodb/spring-data-mongodb-query-document/

Related

Fetching Data from MongoDB according createdAt column only with date

I have collection Ticket_master,which like as follows
Ticket_master
{
_id:5e70ed53de0f7507d4da8dc2,
"TICKET_NO" : 1000,
"SUBJECT" : "Sub1",
"DESCRIPTION" : "Desc1",
"createdAt" : ISODate("2020-03-17T15:31:31.039Z"),
}
Already tried with the following code snippet and it returns null result set.
db.getCollection('ticket_masters').find({ 'createdAt':ISODate('2020-03-17T00:00:00.000Z')})
How fetch fetch data from ticket_master collection by matching the value with date of creation column,which is represented as createdAt.
Following code snippets return the results. Because it contain both date and time.How fetch data from the collection only with Date .
db.getCollection('ticket_masters').find({ 'createdAt':ISODate('2020-03-17T15:31:31.039+00:00')})
as long as you are searching for all the tickets that have been created on some day, so you can use a date range to filter the tickets
db.getCollection('ticket_masters').find({
createdAt : {
$gte: ISODate('2020-03-17T00:00:00.000Z'),
$lt: ISODate('2020-03-18T00:00:00.000Z')
}
})
this should return all the tickets that have been created on 17/03/2020
check this Mongo Playground

Why does yii2 mongodb date filter returns no results when using between condition

I am using yii2 mongodb latest version, when i try to get record in a given date range i get null records. my codes are as follow
Function that filter records received today that is in my model
public function today(){
$finder = self::find();
$startDay = strtotime('midnight',time())-1;//start of day
$endDay = time(); //now
$d1=to_isoDate($startDay);
$d2=to_isoDate($endDay);
$args=['created_at'=>['$gte'=>$d1,'$lte'=>$d2]];
$finder->andWhere($args);
return $finder;
}
Function that converts time-stamp to UTCDateTime, when inserting to collection or create a query i call this function
function to_isoDate($timestamp){
return new \MongoDB\BSON\UTCDateTime($timestamp);
}
Trying to get all models that were created today returns nothing yet i have records for the day
One of the mongo document is as follow
{
"_id" : ObjectId("5892deb01c80f22a180af457"),
"title" : "TEST",
"content" : "we are",
"slug" : "test",
"guid" : "5892deae76036",
"type" : "sms_outbox",
"mime" : ObjectId("5891ae441c80f24e4057f332"),
"meta" : {
"from" : "5891d0a51c80f2131d327b92",
"scheduled" : "0"
},
"alias" : "+254723681977",
"parent" : "5891ae071c80f2394e688db5",
"status" : "sent",
"created_at" : ISODate("2017-01-01T07:24:30.000+0000"),
"updated_at" : ISODate("2017-02-02T07:24:30.000+0000"),
"updated_by" : "588899ac1c80f227512d1102",
"created_by" : "588899ac1c80f227512d1102"
}
Kindly assist to troubleshoot what am doing wrong
I had a similar issue today, multiplying the $timestamp by 1000 resolved the issue and the date filter works fine now.
Here is the modified to_isoDate method:
function toIsoDate($timestamp){
return new \MongoDB\BSON\UTCDateTime($timestamp * 1000);
}
You also need to modify your query to look like this:
public function today(){
$finder = self::find();
$startDay = strtotime('midnight',time())-1;//start of day
$endDay = time(); //now
$d1= toIsoDate($startDay);
$d2= toIsoDate($endDay);
$finder->andWhere(['>=', 'created_at', $d1]);
$finder->andWhere(['<=', 'created_at', $d2]);
return $finder;
}
Reference: https://github.com/yiisoft/yii2-mongodb/issues/181
I hope this helps someone, I spent quite some time trying to find a solution to this.

mongo find query on joda datetime

i am trying to use find query in mongodb to determine the records on that specific date , the query is working fine when i pass it the normal date object and if i find according to dateCreated field, but for joda date field, i don't know how should i form a joda date
right now i am using this query for normal records
var from = new Date('2015-05-18T00:00:00.000Z');
var to = new Date('2016-05-19T00:00:00.000Z');
db.delivery.find( {"dateCreated" : { $gte:from,$lt:to } } );
now i also have a field called deliveryDate which is of type joda date and stored like this
"deliveryDate" : {
"jodaType" : "org.joda.time.DateTime",
"interval_start" : ISODate("2015-03-28T18:30:00Z"),
"interval_end" : ISODate("2015-03-28T18:30:00Z"),
"jodaField_zone" : "UTC",
"time" : NumberLong("1427567400000"),
"jodaField_dayOfMonth" : 28,
"jodaField_hourOfDay" : 18,
"jodaField_minuteOfHour" : 30,
"jodaField_millisOfSecond" : 0,
"jodaField_monthOfYear" : 3,
"jodaField_year" : 2015
},
i googled a lot but with no success, i have no idea how can i query for joda date ,please help!
Your joda date is serialised into a nested JSON object. You should be able to query on it using interterval_start
db.delivery.find( {"deliveryDate.interval_start" : { $gte:from,$lt:to } } );

Query a Timestamp in MongoDB

MongoDB document sample is given below:
{
"_id" : ObjectId("5f2df113bdde22f1043g45gg"),
"cd" : 1395376406,
"dob" : 552026006,
"e" : "test#gmail.com",
"g" : "M"
}
I need query to get birthday list for today using dob(date of birth) field(timestamp).
Thanks in advance!
I am not sure how elegant my solution is, but it should work
var start = new Date();
start.setHours(0,0,0,0);
var end = new Date();
end.setHours(23,59,59,999);
db.collection.find({dob:{$gt:start.getTime(), $lt:end.getTime()}})
Since MongoDb doesn't have any inbuilt functions/operations to support parsing raw timestamps and extracting information from them, you need to do the operation by passing a custom java script function to the server and get it executed there. This function would be executed for each record though.
db.collection.find({$where:function(){
var recDate = new Date(this.dob);
var recDay = recDate.getDate();
var recMonth = recDate.getMonth();
var today = new Date();
var todayDate = today.getDate();
var todayMonth = today.getMonth();
return (recDay == todayDate && recMonth == todayMonth);
}});
The function simply checks if any record's day and month match today's day and month.
Although this works for timestamps, you should take advantage of MongoDBs ISODate data type whenever you store date information. This enables us to use various operators and functions on these fields. Moreover they would be faster. If your document had the below structure:
{
"_id" : "1",
"cd" : 1395376406,
"dob" : ISODate("2014-11-19T08:00:00Z"),
"e" : "test#gmail.com",
"g" : "M"
}
Where, the dob field is of ISODate type. You could easily do a aggregate operation to fetch the results.
var todayDate = ISODate().getDate();
var todayMonth = ISODate().getMonth();
db.collection.aggregate([
{$project:{"day":{$dayOfMonth:"$dob"},
"month":{$month:"$dob"},
"_id":1,"cd":1,"dob":1,"e":1,"g":1}},
{$match:{"day":todayDate,"month":todayMonth}},
{$project:{"cd":1,"dob":1,"e":1,"g":1,"_id":1}}
])
The above operation utilizes the functions and operations that are allowed on a ISODate field. Querying becomes a lot easier and better.

Forming queries with comparison query operators and ISODate from groovy to get data from mongodb

Here is my sample JSON from eventSchedule collection in mongodb:
/* 0 */
{
"_id" : ObjectId("51cd841b8b757a8c4c3b0af9"),
"type" : "evo",
"eventInfo" : {
"title" : "My title",
"field1" : "MyField1",
"schedule" : {
"fromDate" : ISODate("2013-07-19T04:00:00Z"),
"toDate" : ISODate("2013-07-25T20:00:00Z")
}
},
"locationName" : "Loc1"
}
I want to query this collection and get all eventSchedules with schedule field "fromDate" after the present date.
In mongoVUE, following query works:
db.eventSchedule.find({ "eventInfo.schedule.fromDate" : { "$gte" : ISODate("2012-04-29T00:00:00Z") } }).limit(50);
I am trying to do it from one of my grails controller as:
def curDate= new Date()
def sdf= new SimpleDateFormat("yyyy-mm-dd")
def curFormattedDate= sdf.format(curDate)
def queryVal= "{\$gte : ISODate(\""+curFormattedDate+"T00:00:00.000Z\")}"
query.put("eventInfo.schedule.fromDate:", queryVal.trim())
DBObject a = db.eventSchedule.findOne(query)
println a
Above code returns the value of a to be null. Pls note that if i remove the enclosing braces from queryVal, then also it does not work.So can anyone help me form the appropriate query in groovy?
There are few areas where you need to rectify creating the query:
mm in date format represents minutes and not Month. Use MM instead.
Don't you need to escape " for $gte if you really want to stick to the mongoVUE version?
def queryVal= "{\"\$gte\" : ISODate(\""+curFormattedDate+"T00:00:00.000Z\")}"
BTW, a groovier way to format date is
def currentFormattedDate = new Date().format('yyyy-MM-dd')