我的收藏有一個phonenumber欄位。我想在電話號碼前加 91。
{
"_id": "6137392141bbb7723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":9000000001
},
{
"_id": "6137392141bbe30723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":9000000002
}
我想像這樣更新我的收藏。
{
"_id": "6137392141bbb7723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000001
},
{
"_id": "6137392141bbe30723",
"email": "[email protected]",
"lastname": "Cagle",
"firstname": "Brooke",
"phonenumber":919000000002
}
我正在嘗試使用此代碼,但它沒有更新該欄位。
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
});
})
對于這樣的所有檔案,我只得到一個值:
{
"_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
}
我不知道這種方法是否正確。
uj5u.com熱心網友回復:
我找到了解決方案。也許,這行得通,
let mobile = 9876543210;
let phone = `91${mobile}`;
let final = Number(phone)
console.log(typeof(final), final 3);
所以,
var phone = d.phonenumber;
var newPhoneNumber = Number(`91${phone}`);
console.log(newPhoneNumber);
閱讀有關 Number() 的更多資訊:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
uj5u.com熱心網友回復:
操場
db.collection.update({},
//To match all documents
[{
$set: {
key: {
$toInt: {
$concat: [
"91",
{
$toString: "$key"
}
]
}
}
}
}
],
//Concatenate 91 and the value in the field
{multi: true
})
這適用于 4.2 的 mongo 版本。這是用于更新查詢的聚合管道。
參考
編輯:
你會得到溢位錯誤。在這種情況下,您可以使用 toLong。
db.mybooks.update({},
//To match all documents
[{
$set: {
key: {
$toLong: {
$concat: [
"91",
{
$toString: "$key"
}
]
}
}
}
}
],
//Concatenate 91 and the value in the field
{multi: true
})
它是經過測驗的一段代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/417624.html
標籤:
上一篇:postauthorId在mongodb的節點js中變成作者用戶名
下一篇:如何洗掉貓鼬中所有集合的所有檔案
