Update Hour (not date) in MongoDB Date Object

Michael Seltenreich

Is it possible to update the hour for a date entry on an mongo document without recalculating the entire date?

Here is my schema:

book = {
    name: String,
    release: Date
}

Here are some documents:

{name:"book1", release: ISODate("2016-05-18T16:00:00Z")}
{name:"book1", release: ISODate("2016-05-17T17:00:00Z")}
{name:"book1", release: ISODate("2016-03-12T01:00:00Z")}

and so on.

As you can see, the hours for the books are 16:00, 17:00, and 01:00.

I would like to set all the hours to 00:00 while keeping the actual day, month and year unchanged

Is that possible?

Dan Green-Leipciger

Here is a mongo shell script that will set the hour to 00 local time, keep in mind that it will store it in UTC time which may be different than your local time.

var collection = db.YOUR_COLLECTION;
var allBooks = collection.find().toArray();

allBooks.forEach(function(book){
  var updatedDate = new Date(book.release.setHours(0))
  collection.update({_id: book._id}, {release: updatedDate})
});

n.b. I ran this in Studio 3T (formerly Mongo Chef)

Further reading:

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related