Date conversion in mongodb - mongodb

I have a Timestamp field in my collection. The format in which it is storing is "2016-02-06 20:24:39 -0500".
I need to convert in ISODate in mongodb CLI. Can any one suggest me how to convert the date in ISODate format.

We can do something with a MongoDB function in a loop. For example, I have the following document;
{
"_id" : ObjectId("58b036ff8f79f3a0ab96a1cd"),
"date" : "2016-02-06 20:24:39 -0500"
}
I can convert the string value of date to an ISO format with this query
db.getCollection('test').find({_id:ObjectId("58b036ff8f79f3a0ab96a1cd")}).forEach( function(doc) {
var objDate = ISODate(doc.date); //Make an ISO date
doc.date = objDate; //Overwrite the value
db.test.save(doc); //Save the document
});
Now, the document will look like this;
{
"_id" : ObjectId("58b036ff8f79f3a0ab96a1cd"),
"date" : ISODate("2016-02-06T20:24:39.000Z")
}

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

How to convert a date stored as string in MongoDB to ISODate?

I have a collection in which each document has a time field with value stored as similar to "21-Dec-2017".
I want to convert this to ISODate using projection.
My Query:
db.getCollection('orders').aggregate([{
$project:{time : {$add : new Date("$time")}}
}])
But this is returning me ISODate("1970-01-01T00:00:00.000Z") always.
you can try this,
db.getCollection('orders').aggregate([{
$project: {
time: {
$dateToString: {
format: "%d-%m-%G",
date: new Date("$time")
}
}
}
}
])
there is no any string function to get months name eg.Jan,Feb..Dec.
but you can refer https://docs.mongodb.com/manual/reference/operator/aggregation/dateToString/
to more information.
There is no problem in this ISODate("1970-01-01T00:00:00.000Z") format.
you should store date in ISO format but change format on client side according to you.
Basically you want to show date in dd/mm/yy format.
You can use http://momentjs.com/ to show date according to you.

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.

Mongodb : Why convert string date to ISOdate if comparison operators work?

I have the following kind of document:
{
"_id" : ObjectId("538d64a11ca6e50941fda4d9"), "_id" : "538d518e20b8fd642e0000e8",
"posts" : "some stuff", "date" : "2014-06-02"
}
Using comparison operators for a string date (Not the Mongodb ISODate) works:
> collection.find({"date": {"$gte": "2014-06-02"}})
So why shall we (bother to) convert string dates to an ISODate then?
Probably the biggest advantage of using the MongoDB BSON Date type instead of a string is that you can only use the aggregate Date operators with BSON Date values.
But if you don't need to do any aggregation of your data, using a sortable string format to represent dates is fine and often cleaner as you don't need to deal with time zone related display problems.