在shell中,我的查询是:
db.checkin_4e95ae0926abe9ad28000001.update({location_city:"New York"}, {location_country: "FUDGE!"});
但是,它实际上并没有更新我的记录。它也没有错误。运行此操作后执行db.checkin_4e95ae0926abe9ad28000001.find({location_city:"New York"});
后,我得到了所有结果,但location_country
没有更改:
{
"_id": ObjectId("4e970209a0290b70660009e9"),
"addedOn": ISODate("2011-10-13T15:21:45.772Z"),
"location_address1": "",
"location_city": "New York",
"location_country": "United States",
"location_latLong": {
"xLon": -74.007124,
"yLat": 40.71455
},
"location_source": "socialprofile",
"location_state": "New York",
"location_zip": ""
}
答案 0 :(得分:28)
这是因为在update函数的第二个参数中,您需要使用$set运算符来更新location_country
,如下例所示:
db.checkin_4e95ae0926abe9ad28000001.update(
{location_city:"New York"}, //find criteria
// this row contains fix with $set oper
{ $set : { location_country: "FUDGE!"}});
Here您可以找到可用更新运算符列表。
答案 1 :(得分:6)
在版本3.6中更改。 以下是update的语法:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
示例:
db.getCollection('products').update({},{$unset: {translate:1, qordoba_translation_version:1}}, {multi: true})
在您的示例中:
db.checkin_4e95ae0926abe9ad28000001.update(
{location_city:"New York"}, //query
// $update query
{ $set : { location_country: "FUDGE!"}});
默认情况下,update()方法更新单个文档。设置“多参数”以更新所有符合查询条件的文档。
示例2:
db.checkin_4e95ae0926abe9ad28000001.update(
{location_city:"New York"}, //query
// $update query
{ $set : { location_country: "FUDGE!"}}, {multi: true});
答案 2 :(得分:4)
db.m_country.update(
{"countryId": "962a0935-bf3d-4f63-a53c-254760273ede"},
{$set: {'countryPopulation': '12540000'}})
答案 3 :(得分:0)
更新前
> db.student.find({name:"Venky"}).pretty();
{
"_id" : ObjectId("6012e64dc2979ddffe1e5df9"),
"name" : "Venky",
"dept" : "MCA",
"age" : "26",
"phone" : "89786465"
}
<块引用>更新命令
> db.student.update({name:"Venky"},{$set: {name:"DODDANNA CHAWAN",dept:"MCA(CS)", age:"25", phone:"1234567890"}});
<块引用>
查找命令查看结果
> db.student.find({name:"DODDANNA CHAWAN"}).pretty();
<块引用>
更新结果后
{
"_id" : ObjectId("6012e64dc2979ddffe1e5df9"),
"name" : "DODDANNA CHAWAN",
"dept" : "MCA(CS)",
"age" : "25",
"phone" : "1234567890"
}
<块引用>在现实生活中使用唯一的“_id”来匹配文档,因为名称会被发现为重复