Home > Enterprise >  MongoDB: Update 1 field in each document in a collection
MongoDB: Update 1 field in each document in a collection

Time:10-06

I have a mongo collection that consist of many documents but I want to update a single field that is currently a string to a ISODate object.

Collection = { 
   { _id: ObjectId('1'), date: '2022-01-01T01:00:00.000Z' },
   ...
};

What I am looking for

Collection = { 
   { _id: ObjectId('1'), date: ISODate('2022-01-01T01:00:00.000Z') },
   ...
};

I figured I could go do a db.get('Collection').find({}).forEach(... update logic); but I am unsure how I would set that up.

I appreciate any type of help

EDIT: I figured it out after receiving some help

db.getCollection('Collection').find({"date": { "$exists": true, "$type": 2 }}).forEach(function (doc) {
    var newDate = new Date(doc.date);
    db.getCollection('Collection').findAndModify({query: { "_id": doc._id }, update: {
        $set: {
            "date" : newDate
        }
    }})
})

CodePudding user response:

Don't do find().forEach() because it's going to cause you to stream all of the data to the client and then back.

Instead, just issue an update that can be executed on the server by itself. The general approach is documented here. For your specific situation you want something like this:

db.collection.update({},
[
  {
    $set: {
      date: {
        $dateFromString: {
          dateString: "$date"
        }
      }
    }
  }
])

Working playground example here.

  • Related