Ruby
Ruby

Reputation: 33

MongoDB type a attribute of document in collection

I am currently working on a project that save regulary data to a MongoDB database. In this database I have a several element and each document contains date.

Problematic

The documents contains wrong type for date attribute. enter image description here It's due of bad inserting, all documents have a date in string format. I can per one update each attribute with MongoDB Atlas graphical interface, but this solution is too long..

Question

I wanted to know if in MongoDB we have a solution to update the type of an attribute in all documents in a collection.

Upvotes: 1

Views: 314

Answers (2)

ray
ray

Reputation: 15276

For your case, the simplest solution is using $toDate in an update with aggregation pipeline

db.collection.update({},
[
  {
    "$addFields": {
      "date": {
        "$toDate": "$date"
      }
    }
  }
])

Here is the Mongo playground for your reference.

If you need to cater with other date format, you can use $dateFromString.

db.collection.update({},
[
  {
    "$addFields": {
      "date": {
        "$dateFromString": {
          "dateString": "$date",
          "format": <your format here>
        }
      }
    }
  }
])

You can refer to this official documentation on $dateFromString regarding the format parser.

Upvotes: 1

Mohammad Zafardoost
Mohammad Zafardoost

Reputation: 81

If I understand correctly, you can try these:

db.collection.aggregate([
    { "$addFields": {
        "date": {
            "$toDate": "$date"
        }
    } }
])

db.collection.aggregate([
    { "$addFields": {
        "date": { 
            "$convert": { 
                "input": "$date", 
                "to": "date" 
            } 
        }
    } }
])

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

var bulkOps = [];
var cursor = db.collection.find({});

cursor.forEach(function (doc) {
  var newDate = new ISODate(doc.date);
  bulkOps.push(
    {
      "updateOne": {
        "filter": { "_id": doc._id },
        "update": { "$set": { "date": newDate } }
      }
    }
  );
});

if (bulkOps.length > 0) {
  db.collection.bulkWrite(bulkOps);
}

Upvotes: 1

Related Questions