Date conversion in Mongo Db - mongodb

I am having trouble converting "7/26/2020 18:34:25" into any date format from which Mongo can run aggregate operation.
The date in the Mongo is stored as string.
I have tried "$toDate", "$convert" and "$dateToString".

You need to use $dateFromString
$project: {
date: {
$dateFromString: {
dateString: '$dateFieldName',
format: '%m/%d/%Y %H:%M:%S'
}
}
}
playground

Try using Moment Library for converting you date
In your case this code can help you:
moment('7/26/2020 18:34:25').toDate();
You can test this code on browser side on this page
enter link description here

Related

MongoDB: Migrate some YYYY-MM-DD dates to ISO 8601

I have a field with dates stored in different formats (due to a code change at some point):
Some documents in the same collection use ISO 8601 ("2022-06-27T00:00:00.000Z"), while some others use the YYYY-MM-DD syntax ("2022-06-27").
This is a problem, because this query fails to fetch the YYYY-MM-DD documents (while it does fetch the ISO ones):
filter:
{"where":{"and":[{"notificationOfNeedDate":{"gte":"2019-04-08T21:00:00.000Z"}}]},"order":["aCode DESC"],"limit":24,"skip":0}
I believe the solution is to migrate all YYYY-MM-DD to ISO dates
Is there a command to run in mongodb in order to "UPDATE" all YYYY-MM-DD to ISO dates (for that collection and field), respecting the locale timezone offset and the DST settings for that day?
Thanks
Another example why date values should never be stored as string, it's a design flaw. Store always proper Date objects, so you go in the right direction.
Your question is not really clear, string "YYYY-MM-DD" is also a valid format according to ISO 8601 (a date, just without time information).
You can use $dateFromString:
db.collection.updateMany(
{ timestamp: { $type: "string" } },
[ {
$set: {
notificationOfNeedDate: {
$dateFromString: {
dateString: '$notificationOfNeedDate',
timezone: 'Europe/Athens'
}
}
}
} ]
)
You don't need to specify format, because ISO-8601 format is the default.
Then in your query you need to filter also on Date values:
db.collection.find({ notificationOfNeedDate: { $gte: ISODate("2019-04-08T21:00:00.000Z") } })
Of course, ISODate("2019-04-09T00:00:00+03:00") works also

Searching for MongoDB ISODate Using Spring Data #Aggregation

I have a Spring API connecting to a MongoDB database. I am trying to use Spring's #Aggregation to find entries in a "Shipment" document which have a "shipDate" later than the date specified by the user.
Here is an example of my repository:
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ShipmentRepository extends MongoRepository<Shipment, String> {
#Aggregation("{ '$match': { shipDate: {$gt: ISODate(?0)} } }")
int findShippedAfterDate(String date);
}
The value being passed as date is "2020-06-16". I am using #Aggregation instead of #Query because there will be a $group opperation following the $match once I get this portion working.
It seems that using ?0 inside ISODate() does not work properly and results in the following error:
JSON reader expected a string but found '?0'
I have tried the following syntax variations:
shipDate: {$gt: ISODate('?0')}
shipDate: {$gt: ISODate('$?0')}
Both result in the following error, which I believe is caused by ?0 not actually being replaced by the value:
org.bson.json.JsonParseException: Invalid date format.
I am confident the issue is with ?0 not being replaced by the string value because the query works as expected when the string is used instead of the variable place holder:
#Aggregation("{ '$match': { shipDate: {$gt: ISODate('2020-06-16')} } }")
Is there a simple syntax mistake I am making? Thanks for any help on this!
I was able to get this working by using $dateToString to convert the ISODate stored in MongoDB to a string that can be matched against the date provided by the user and then adding it to each entry using $addFields. However, I believe this method may have the following issue:
Inefficient because it will add a dateString field to every returned entry.
I'm am not certain that this will be an issue because it depends on how MongoDB handles $addFields when followed by $match. If it only adds the field to entries that are returned by the $match, it will be much more efficient.
Working #Aggregation example:
#Aggregation(pipeline = {
"{ '$addFields': { 'dateString': { $dateToString: { format: '%Y-%m-%d', date: '$shipDate'} } } }",
"{ '$match': { dateString: {$gte: ?0} } }" })

dateFromString not covering valid date

I am trying to covert a date in Mongo. We are not yet on 4.0 so I have to use dateFromString.
My date is stored is a valid date: "2019-02-05T03:38:52.441Z"
I can do this on my local 4.0.6 and this works great!
{ $toDate: "$eventTime" }
but I need to run this on an older version of Mongo.. and I changed to this:
{ $dateFromString: { dateString: "$eventTime" }}
I get the following error:
"$dateFromString requires that 'dateString' be a string, found: date with value 2019-02-05T03:38:52.441Z"
Looks like a valid date to me... any ideas? Other than upgrading Mongo :)
I had to add this to my test data:
var ISODate = require('isodate');
ISODate("2019-08-13T17:54:00.800Z"),

I can not get dates after my current date

I want to obtain the records that the "FECHA_FIN" field is greater than or equal to today's date.
this is an example of my data:
but with this query:
db.getCollection('susp_programadas').find( {"FECHA_FIN":{ $gte: new Date("YYYY-mm-dd") }} )
I do not get results, what am I doing wrong? Thank you
You can convert the date to an ISO date and query that way. Since you stored the date as a string mongo has no idea how to query it against an ISO date without conversion.
If you stored your date in mongo as the default ISO date then you could have easily done this:
db.getCollection('susp_programadas').find({"FECHA_FIN":{$gte: new Date()}})
So this is how you can do it now:
db.getCollection('susp_programadas').aggregate([
{
$project: {
date: { $dateFromString: { dateString: '$FECHA_FIN' }}
}
},
{ $match: { date: { $gte: new Date() }}}
])
You can use the $dateFromString in an aggregate query with a $match to get the results you want. Note that $dateFromString is only available in MongoDB version 3.6 and up.
If there is no way to convert your data to ISODate or upgrade your DB you could also consider another solution which via $where:
db.getCollection('susp_programadas').find({
$where: function(){
return new Date(this.FECHA_FIN) > Date.now()
}
})
However that solution suffers from the fact that $where can not use indexes so have that in mind.

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.