Ikkyy
Ikkyy

Reputation: 66

Changing a array type in mongodb

I am trying to change an array type inside my collection on MongoDB.

title: ['1', '2', '3']

to: [1,2,3]

I already changed at the model to:

title: [{
    type: Number,
}], 

Already tried:

Users.updateMany({ title: "1" }, { $set: { 'titulos.$': 1} }, { safe: true, upsert: true }, function (err, doc) {
    if (err) {
        console.log(err);
    }
});

Can someone help me ?

Upvotes: 0

Views: 47

Answers (1)

mickl
mickl

Reputation: 49945

Since you're looking for a one-time operation and you're using MongoDB 4.0, the easiest way would be to take advantage of $addFields, $map and $toInt to replace existing title for every user and then run $out to replace exising MongoDB collection (make sure it's named users in your database):

await User.aggregate([
    {
        $addFields: {
            title: {
                $map: {
                    input: "$title",
                    in: { $toInt: "$$this" }
                }
            }
        }
    },
    { $out: "users" }
])

Upvotes: 2

Related Questions