Home > Net >  how to add number to field in every doucment in monogdb using nodejs
how to add number to field in every doucment in monogdb using nodejs

Time:01-18

my collection has phonenumber field. i want to add 91 infront of phonenumber.

{
"_id": "6137392141bbb7723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":9000000001
},
{
"_id": "6137392141bbe30723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":9000000002
}

i want to update my collection like this.

{
"_id": "6137392141bbb7723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000001
},
{
"_id": "6137392141bbe30723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000002
}

im trying with this code but its not updating the field.

var x = await User.find({});
        x.forEach(async function(d)
            { 
                var phone = d.phonenumber;  
                var newPhoneNumber = 910000000000 phone;
                console.log(newPhoneNumber);

                //update 
            await User.updateMany({},{$set:{phonenumber:newPhoneNumber}},
                {
                    new: true, 
                    runValidators : true
                });
            })

im getting only one value for all documents like this:

{
"_id": "6137392141bbb7723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000001
},
{
"_id": "6137392141bbe30723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000001
},
{
"_id": "6137392141bbe30723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000001
}

i don't know whether this approach is correct or not.Thank you

CodePudding user response:

Playground

db.collection.update({},
//To match all documents
[{
  $set: {
    key: {
      $toInt: {
        $concat: [
          "91",
          {
            $toString: "$key"
          }
        ]
      }
    }
  }
}
],
//Concatenate 91 and the value in the field
{multi: true
})

This is applicable for mongo versions from 4.2. This is aggregation pipeline which is used in update query.

Reference

CodePudding user response:

I have found a solution. Maybe, this works,

let mobile = 9876543210;
let phone = `91${mobile}`;
let final = Number(phone)
console.log(typeof(final), final 3);

So,

var phone = d.phonenumber;
var newPhoneNumber = Number(`91${phone}`);
console.log(newPhoneNumber);

Read more about Number() : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

  •  Tags:  
  • Related