28

在 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": ""
}
4

4 回答 4

32

这是因为在更新函数的第二个参数中,您需要使用$set运算符来更新location_country,如下例所示:

db.checkin_4e95ae0926abe9ad28000001.update(
   {location_city:"New York"}, //find criteria
   // this row contains fix with $set oper
   { $set : { location_country: "FUDGE!"}}); 

您可以在此处找到可用更新运算符的列表。

于 2011-10-13T16:08:57.997 回答
17

在 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});
于 2018-08-09T18:14:27.553 回答
8
db.m_country.update(
    {"countryId": "962a0935-bf3d-4f63-a53c-254760273ede"}, 
    {$set: {'countryPopulation': '12540000'}})
于 2018-07-06T05:13:24.460 回答
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”来匹配文档,因为名称将被发现为重复项

于 2021-01-29T11:18:34.087 回答