• MongoDB

    MongoDB Change the data type of a field

    Problem: I want to change the data type of a field in my MongoDB collection from string to Date. Example: I have a field in my collection called expiry which has values stored in string like 31 Dec 2021 . I need to change this to a Date object. Solution: db.posts.find({}).forEach(function (doc) { db.posts.updateOne( { _id: doc._id, }, { $set: { expiry: new Date(doc.expiry) }, } ) }) The above shell command will find all collections in my posts collection and change the data in expiry field which is of type string to Date