1

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"
}
3
  • Could you post sample collection and the version you are using Commented Sep 23, 2018 at 7:34
  • MongoDB version is 3.6.2. Commented Sep 23, 2018 at 7:41
  • @AnthonyWinzlet updated the question Commented Sep 23, 2018 at 7:44

2 Answers 2

1

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) }}
   ); 
 }
);
Sign up to request clarification or add additional context in comments.

Comments

0

You can try below $out aggregation

db.collection.aggregate([
  { "$addFields": {
    "TimeStamp": {
      "$dateToString": {
        "format": "%d-%m-%Y",
        "date": { "$dateFromString": { "dateString": "$TimeStamp", "format": "%m-%d-%Y" }}
      }
    }
  }},
  { "$out": "collection_name" }
])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.