siva prasad
siva prasad

Reputation: 55

Update particular field in mongodb of all documents with reference to its current value

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

Answers (2)

Adi Levin
Adi Levin

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

Ashh
Ashh

Reputation: 46481

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" }
])

Upvotes: 0

Related Questions