mongodb – convert values of each object in an array

Ok so I kept digging and found that I needed to use $map. https://docs.mongodb.com/manual/reference/operator/aggregation/map/

Here is it :

db.coll.updateOne(
    {username: "JohnDoe"},
    [{$set: {
        "activities": {
            $map: {
                input: "$activities",
                in: {
                    name: "$$this.name",
                    lastTime: {$toDate: "$$this.lastTime"},
                }
            }
        }
    }}]
)

EDIT :

Or better, if I just want to change the “lastTime” field :

db.coll.updateOne(
    {username: "JohnDoe"},
    [{$set: {
        "activities": {
            $map: {
                input: "$activities",
                in: {
                    $mergeObjects: ["$$this",{lastTime: {$toDate: "$$this.lastTime"}}]
                }
            }
        }
    }}]
)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top