我的db结构为;
"name" : "alex"
"age" : "21"
"location" : "la"
"name" : "felix"
"age" : "1"
"location" : "la"
如果数据库中的名称和年龄字段等于我的查询中的值,我想更新位置字段。
例如,如果我写的话;
db.collection.update({name: "alex", age: "32"}, {$set: {location: "ny"}} ,{upsert: true})
它将新元素作为
插入name: alex
age: 32
然而,我想做的是;如果location
为name
且alex
为age
,则更新21
。删除upsert
可以是一种解决方案,但是,我将其用于插入和更新,因此不应删除upsert
。
我如何在node.js中处理这个问题?
编辑:我要做的是;
db.collection.update({name: "alex", age: "32"}, {$set: {location: "ny"}} ,{upsert: true})
返回false,因为alex是21岁。位置无法设置。
db.collection.update({name: "alex", age: "21"}, {$set: {location: "ny"}} ,{upsert: true})
设置位置。
"name" : "alex"
"age" : "21"
"location" : "la"
db变为
"name" : "alex"
"age" : "21"
"location" : "ny"
"name" : "felix"
"age" : "1"
"location" : "la"
答案 0 :(得分:0)
当有upsert:true时,mongo将此字段添加到所有集合对象(甚至创建新文档),因此当您没有字段位置时,它将被创建。 Upsert被认为是在文档范围而不是字段范围。
db.collection.update({name: "alex", age: "21"}, {$set: {location: "ny"}})