当我更新记录时,它会删除现有字段并添加新字段。
这是更新前的记录:
db.collection('profiles')
.update({
'_id' : obj("56a356863aa433ae37dc2cee") },
{"first_name" : first_name, "last_name" : last_name, "email" : email},
function (err, result) {
console.log(result);
});
这是我执行的命令:
update
这是我执行{ "_id" : ObjectId("56a356c9a08487ed3719e40a"), "first_name" : "kaushik", "last_name" : "makwana", "email" : "kdmakwana" }
命令后的记录:
let someDict = ["matchingString" : [6,7,5,4]]
var someNumber = 5
var someString = "matchingString"
for (someDictKey, numbers) in someDict {
if someDictKey == someString {
// Key Found
for number in numbers {
if number == someNumber {
// Number Found
} else {
// no matching number found
}
}
} else {
// No matching key found
}
}
答案 0 :(得分:5)
与更新现有集合字段相同,如果指定字段不存在,$ set将添加新字段。
> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }
答案 1 :(得分:2)
使用$set
更新字段或添加新字段。您的查询应该是:
db.collection('profiles').update(
{
'_id' : obj("56a356863aa433ae37dc2cee")
},
{ $set:{{"first_name" : first_name, "last_name" : last_name, "email" : email}} },
function (err, result){
console.log(result);
});