How to convert date format in mongodb - mongodb

I am using an API (so I have no control over the fields) - one of the fields is of type Date.
Now, I find that the date stored in the records resembles the following value:
{
...
"foobarDate": "2013-05-26T05:00:00.000Z",
...
}
Now I wish to retrieve some records based on this date - for example, I need to retrieve all the records whose fooBarDate is earlier than today's date.
If I use Javascript's Date() functionality, then I get the date in the following format:
Wed Jun 19 2013 21:13:50 GMT+0530 (IST)
If I try to design my query as follows...
{
"fooBarDate": {
"$lte": <the date calculated in javascript>
}
}
...I do not get the records - I get an empty array - I suspect it is due the reason that the format of the Date stored in MongoDB is different from the one I am passing.
How to convert the Javascript date format to the mongodb format? Or at least, how do I get the current date in the format stored in MongoDB?
P.S. I am using nodeJs and wish to query the DB in this case.

Mongo stores dates as ISODate objects. Just wrap our date into ISODate constructor:
{
"fooBarDate": {
"$lte": ISODate("2013-05-26T05:00:00.000Z")
}
}

The correct data format if you pass a string into the query is ISO8601 which is looks like you have done, however you can also pass the javascript date object into the query directly and get the same result. It looks like you may be missing the proper brackets which could be causing your query to fail. Try reformatting your code in this manner (edit I am using mongoose, but I think straight mongo is the same):
var currentTime = new Date;
orm.Records.find({lastUpdate:{$lte:currentTime}})

Related

Is there a way we can get date alone from a datetime field stored as string in MongoDB. We are using Spring MongoDB driver

Let's say I have an date attribute stored in the format dd/MM/YYYY HH:mm:ss i.e. 22/12/2021 10:15:23. Now I just want 22/12/2021 as a date value so that I can do date comparisons. I want this operation to happen at database itself so that I can do date comparisons as part of the query/aggregation itself. Please note I am using Spring MongoDB driver.
Getting date alone from a datetime string is not possible in MongoDB since it always returns an ISO date with time. As a workaround we can convert the time HH:mm:ss to 00:00:00 either by applying String operations on the string attribute or by using Arithmetic operations on the date. We will have to add a temporary field in the query which will hold the converted value using add field operations. And then we can compare them with a given date.

MongoDB - Query for date less than returns wrong results

While was querying for documents between two dates (the field type is of Date) like -
db.getCollection('ledgers').find({
created: {
$gt: ISODate("2019-01-19"),
$lt: ISODate("2019-02-19")
}
}).sort({'created':-1})
It was returning documents for the year 2018 also.
MongoDB stores times, not dates. You need to convert your dates to times in your application and query by time ranges.
The date on your post [https://i.stack.imgur.com/XIWhf.png] is 2019-02-18 which is in the range you specified in your query.
I suggest you either provide an example of the error at https://mongoplayground.net/
or correct/delete the question itslef.
Thanks

Date comparison in mongodb

I want to retrieve all the documents after a particular date.
My database has date as - DateAdded:"2014-12-17 10:03:46.000Z"
I wrote the following query-
db.collection.find({DateAdded:{"$lte":new Date("2015-06-17 10:03:46.000Z")}})
But the results doesn't fetches any record even though there are records for the dates upto 2015-06-24.
You can use ISODate to compare dates:
"$lte" : ISODate("2015-06-17T10:03:46Z")
ISODate works because that is the format your date is in.
new Date()
wraps the date in an ISODate helper, but is not able to convert in your query.
Check out this link for more information: https://www.mongodb.com/docs/v4.2/core/shell-types/
Use ISODate
format:
{'field': {$operator: ISODate(yyyy-MM-ddThh:mm:ss.msZ)}}
example:
db.getCollection('yourCollection').find({'sampleField': {$lte: ISODate('2015-06-17T10:03:46.000Z')}})
You can use this:
db.collection.find({DateAdded:{"$lte":new Date("2017-11-01")}})
It will convert your date format into this:
ISODate("2017-11-01T00:00:00Z")

How to convert from string to date data type?

I am uploading data from a csv file to MongoDB. It is taking OrderDate as string data type due to which facing problems while creating reports using a BI tool.
I have about 10000 records in my collection.
Could anyone help me how can I change the data Type of OrderDate to Date with a single query?
I don't think that you can change field's type with single query. The easiest way is to convert data strings into Date format using ISODate function during the insertion. But, if you want to process the data you already inserted, you can do it with the following code using mongodb console:
db.collection.find().forEach(function(element){
element.OrderDate = ISODate(element.OrderDate);
db.collection.save(element);
})
This code will process each element in your collection collection and change the type of Orderdate field from String to Date.
db.messages.find().forEach(function(doc) {
doc.headers.datestamp = new Date(Date.parse(doc.headers.Date.toString()));
db.messages.save(doc);
})
This worked well to convert this sort of text:
Tue, 14 Nov 2007 03:22:00 -0800 (PST)
The text is from an email archive known as the Enron Corpus.

to store date in mongodb

I need to store date in mysql (without time). User inputs date in input box like yyyy-mm-dd, may be later fomat could change.
Could you please tell what is good way to store date in mongodb (without time), we'd use DATE type in mysql? Now whe I need to store date and time I use mongdb date type.
And store it like this:
$data['ADDED'] = new MongoDate(time());
And display them:
echo gmdate('Y-m-d H:i:s', $data['ADDED']->sec);
When I use only date I store them as string like: yyyy-mm-dd (I validate date before storing it to make sure it's correct date). I'll need to find by date something like this:
dateField <(>) somedate
Do you think it's acceptable to store date as string in mongodb? How do you usually store date in mongodb?
MongoDB does not have a DATE type. It instead has a ISODate type. This is just as good for storing "without" time as I will explain.
So you can use MongoDate like so:
$date = new MongoDate(); // Denotes today, just like the date() function
Now to store without time you can just fake it by making PHP only set a date, as such the default time will be 00:00:00 (I should note this does mean a time is actually stored just as 00:00:00):
$date = new MongoDate(strtotime('2012-04-23')); // strtotime for fun
And then you can query by just the date part like:
find(array('date' => new MongoDate(strtotime('2012-04-23'))));
And you can now query as though you don't have a time since the time will equal what you put in: 00:00:00.
Of course this is just one way of fixing it.