i want to update mobile field to string in mongodb.
{
"_id": "1373b7723",
"firstname": "name1",
"mobile":1000000099
},
{
"_id": "137be30723",
"firstname": "name2",
"mobile":1000000088
}
i need an output like this.
{
"_id": "1373b7723",
"firstname": "name1",
"mobile":"1000000099"
},
{
"_id": "137be30723",
"firstname": "name2",
"mobile":"1000000088"
}
db.users.updateMany(
{}, //To match all documents
[{ $set: {mobile: { $concat: [ "", "$mobile" ] } } }],
{
new: true,
runValidators : true
});
i tried with the above code but its not getting the desired output.
I did something similar earlier, but it was not conversion to string but to Date. See this
You can also use $toString as mentioned here. See this example similar to your use case
Try below if it works for you.
db.users.find({}).forEach(function (doc) {
db.users.updateOne(
{
_id: doc._id,
},
{
$set: {
mobile: String(doc.mobile)
},
}
)
})
or modified version of your code
db.users.updateMany(
{}, //To match all documents
[{ $set: {mobile: { $toString: {$toLong:"$mobile"} } } }],
{
new: true,
runValidators : true
});