Folks,
Having a difficult time with moment.js documentation.
record.lastModified = moment.utc().format();
returns:
2014-11-11T21:29:05+00:00
Which is Great, its in UTC... When I store that in Mongo, it gets stored as a String, not a Date object type, which is what i want.
What I need it to be is:
"lastModified" : ISODate("2014-11-11T15:26:42.965-0500")
But I need it to be a native javascript object type, and store that in Mongo. Right now if i store the above, it goes in as string, not Date object type.
I have tried almost everything with moment.js. Their toDate() function works, but falls back to my local timezone, and not giving me utc.
Thanks!
Saving a Javascript Date object will result in an ISODate being stored in Mongo.
Saving an ISO date as a Javascript String will result in a String being stored in Mongo.
So, this is what you want: record.lastModified = new Date(moment().format());
Not an ideal solution, But I achieved the same result, by manually converting it to ISODate object through monogo shell. We need the ISODate for comparison/query for aggregating results, so we run this script before running our aggregate scripts.
Inserting local time string by using moment().format().
"createdDt" : "2015-01-07T17:07:43-05:00"`
Converting to an ISODate (UTC) with:
var cursor = db.collection.find({createdDt : {$exists : true}});
while (cursor.hasNext()){
var doc = cursor.next();
db.collection.update(
{_id : doc._id},
{$set: {createdDt : new ISODate(doc.createdDt)}})
}
results in
"createdDt" : ISODate("2015-01-07T22:07:43Z")"
Note the time got converted
T17:07:43-05:00 to T22:07:43Z
I could not find any solution for inserting BSON ISODate format (which is UTC by default) from JavaScript directly, while inserting a new document, it seems to be available through pyMongo & C#/Java Drivers though. Trying to look for an maintainable solution
Related
I'm retrieving the SQL Date value from sql database using MSSQL node module through node js application but the resultant record set returns the date as Date time value.
2020-11-21 in database is displayed as 2020-11-21T00:00:00
Should we need to handle this explicitly?
This is not "DateTime", that's how toString of a Date object looks like in Javascript:
If you want it to be printed in a certain format that shows only the "date" portion, you can use toLocaleDateString():
const d = new Date()
console.log(d.toLocaleDateString()) // '11/18/2020'
or, if you want the result to be formatted like the example above: yyyy-mm-dd you can do:
d.toISOString().slice(0, 10); // '2020-11-18'
I have been storing some dummy data on a project I've been working on. Some data include dates in the format of date. But somehow, I saw it changed the format to long number and I have no idea why. Can someone please tell me how to convert the format back to dates? I saw someone suggesting using aggregate $todate. EG:
db.getCollection('my_list').aggregate([
{
$project: {
toDate: {
$toDate: "$published_date"
}
}
}
])
I have tried that code above but it was not a permanent change.
The data result I got as a datetime format in python as: 9/11/2019 12:00 PM.... Code as below:
timestamp = '2019-11-09T12:00:12.000Z'
format = "%Y-%m-%dT%H:%M:%S.%fZ"
some_datetime_obj = datetime.datetime.strptime(timestamp, format)
Some_datetime_obj returns a datetime format.
But when it enters mongodb, I get a NumberLong object.
So how do I make a permanent change to all the data in the database?
I figured it out. I don't know why, but how it happened was because I converted my dataframe into a json format then only inserted into mongodb.
OLD CODE:
records = json.loads(df.T.to_json()).values()
vid_client_db[VID_COL].insert_many(records)
NEW CODE:
records = df.to_dict(orient='row')
vid_client_db[VID_COL].insert_many(records)
I am using node.js and Mongo DB in my application.
I have stored date in a field(datetime) of an entry in a MongoDB as:
db.collection('person').insertOne({"name": "ABC","age": "40","datetime": Date()}
This outputs date as:"datetime":"Mon Nov 21 2016 00:47:39 GMT-0500 (Eastern Standard Time)"
Now I am trying to find all entries which are greater than a particular date.
For this I do the following:
db.collection('person').find( {'datetime':{$gt: startingdate})
where startingdate contains 22,11,2016.
This doesn't work and fetches me all the records that have a datetime field.
I even tried using :
startingdate = Date(22,11,2016)
and
startingdate = Date(2016,11,22)
but to no avail. Can someone help me figure this out?
Thanks!
Use new Date() instead of Date().
new Date() returns date object whereas Date() returns string representation of datetime.
You need to send date object to MongoDB so that it can transform the date object to ISODate.
I am trying to return search results for every document that was created on a day. Below is the query I use.
var query = Document.find({}).populate('contacts');
var gte = moment(req.query.date, 'DD-MM-YYYY').startOf('Day');
var lte = moment(req.query.date, 'DD-MM-YYYY').endOf('Day');
query.where('dates.createdAt').gte(gte).lt(lte);
This query works for some days but not all. I can't seem to understand the behaviour. Please help out.
The format of the date in the query string is DD/MM/YYYY.
Works for : 2016-04-16T00:02:30.065Z
Does not work for: 2016-04-15T19:02:59.758Z
It's wrong because you don't initialize as .utc(), and MongoDB dates are stored in UTC:
var gte = moment.utc(req.query.date, 'DD-MM-YYYY');
var lte = moment.utc(req.query.date, 'DD-MM-YYYY').endOf('Day');
And there is no need for the startOf() either.
If you don't construct like that, then the resulting Date object is skewed by the difference in the local timezone. Hence why you don't see the selection working where the hours would cross over dates.
Also if dates are coming in as 01/01/2016 then the format string would be 'DD/MM/YYYY', but one or the other is likely a typo in your question.
At the moment using JavaScript I'm attaching a date to every single object similar to the following.
post.date = getTimestamp(post._id).toDateString();
I can then access 'date' from within my template. Is there a nicer way to extract the date?
I'm not sure if this will work in a template, but:
post._id.getTimestamp();
returns an ISODate.
http://mongodb.github.com/node-mongodb-native/api-bson-generated/objectid.html#gettimestamp
If _id is UUID, then first 8 bytes of it is timestamp.
You may, fore example, extract date as follows:
var date = new Date( parseInt( post._id.substring(0,8), 16 ) * 1000 )