Shaleesh Madhavan
Shaleesh Madhavan

Reputation: 47

MongoDb convert Datetime stamp to date in collection

I have few dates in my collection

"workedDate" : ISODate("2020-07-02T08:16:59Z"),
"workedDate" : ISODate("2020-07-01T14:00:00Z"),
"workedDate" : ISODate("2020-06-30T16:00:00Z"),
"workedDate" : ISODate("2020-06-29T14:00:00Z"),
"workedDate" : ISODate("2020-07-01T23:43:32Z"),

I need the timestamp to be removed like "workedDate" : "2020-07-02" or like this "workedDate" : ISODate("2020-07-02T00:00:00Z")

Need result like this.

"workedDate" : ISODate("2020-07-02T00:00:00Z"),
"workedDate" : ISODate("2020-07-01T00:00:00Z"),
"workedDate" : ISODate("2020-06-30T00:00:00Z"),
"workedDate" : ISODate("2020-06-29T00:00:00Z"),
"workedDate" : ISODate("2020-07-01T00:00:00Z"),

any update query available

Upvotes: 0

Views: 1300

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

I think the below script is what you are looking for

var count = 0;
db.<Collection-Name>.aggregate([
    {
        "$project": {
            "_id": 1,
            "workedDate": 1,
        }
    },
    {
        "$addFields": {
            "DateinString": {
                "$toDate": {
                    "$dateToString": {
                        "format": "%Y-%m-%d",
                        "date": "$workedDate"
                    }
                }
            }
        }
  }
]).forEach (function(it) {
    db.<Collection-Name>.updateOne({
        "_id": it["_id"]
    }, {
        "$set": {
            "workedDate": it["DateinString"]
        }
    });
    printjson(++count);
})
printjson("DONE!!!")

Upvotes: 1

Related Questions