Reputation: 55
In my mongodb collection, i have all documents stored with "TimeStamp" field in 'MM-DD-YYYY' format which was stored as string. I want to update that exiting TimeStamp field to 'DD-MM-YYYY' format in all documents. Can anyone help me writing a query for that.
Example I have documents as below
{
"id" : "1",
"TimeStamp" : "09-22-2018"
},
{
"id" : "2",
"TimeStamp" : "09-23-2018"
}
I want to update them to
{
"id" : "1",
"TimeStamp" : "22-09-2018"
},
{
"id" : "2",
"TimeStamp" : "23-09-2018"
}
Upvotes: 1
Views: 77
Reputation: 5243
You can iterate over all documents and reformat the TimeStamp as follows:
function reformat(date) {
var parts = date.split('-');
return parts[1]+'-'+parts[0]+'-'+parts[2];
}
db.collection.find({TimeStamp : {$exists: true}}).snapshot().forEach(
function (doc) {
db.collection.update(
{ _id: doc._id },
{ $set: { TimeStamp: reformat(doc.TimeStamp) }}
);
}
);
Upvotes: 1