十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

 update() 方法用于更新现有文档中的值,其语法格式如下:
 
 db.collection_name.update(
    
    
    {
        upsert: 
        multi: 
        writeConcern: 
    }
)
 参数说明如下:
 
 【示例】首先我们先向集合中插入以下数据:
 
> db.course.insert([
... {
...     title: 'MongoDB教程',
...     author: '编程帮',
...     url: 'http://www.biancheng.com/'
... },{
...     title: 'HTML教程',
...     author: '编程帮',
...     url: 'http://www.biancheng.com/html/index.html'
... },{
...     title: 'C#教程',
...     author: '编程帮',
...     url: 'http://www.biancheng.com/csharp/index.html'
... }
... ])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
 接着使用 update() 方法修改 title 为“MongoDB教程”的文档中的内容。
 
> db.course.update({title:"MongoDB教程"},{$set:{url:"http://www.biancheng.net/mongodb/index.html"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.course.find().pretty()
{
        "_id" : ObjectId("603209d8e492ab9be9450304"),
        "title" : "MongoDB教程",
        "author" : "编程帮",
        "url" : "http://www.biancheng.net/mongodb/index.html"
}
{
        "_id" : ObjectId("603209d8e492ab9be9450305"),
        "title" : "HTML教程",
        "author" : "编程帮",
        "url" : "http://www.biancheng.com/html/index.html"
}
{
        "_id" : ObjectId("603209d8e492ab9be9450306"),
        "title" : "C#教程",
        "author" : "编程帮",
        "url" : "http://www.biancheng.com/csharp/index.html"
}
 默认情况下,在使用 update() 方法更新文档时仅会更新一个文档,若想要更新多个文档,您则需要将参数“multi”设置为 true,如下所示:
 
db.course.update({title:"MongoDB教程"},{$set:{url:"http://www.biancheng.net/mongodb/index.html"}},{multi:true})
 MongoDB 中的 save() 方法可以使用传入的文档来替换已有文档,若 _id 主键存在则更新已有文档,若 _id 主键不存在则作为新数据插入到集合中。语法格式如下:
 
 db.collection_name.save(
    
    {
        writeConcern: 
    }
)
 参数说明如下:
 
 【示例】使用 save() 方法更新 _id 为“603209d8e492ab9be9450304”的文档中的数据。
 
> db.course.save(
... {
... "_id" : ObjectId("603209d8e492ab9be9450304"),
... "title" : "MongoDB教程",
... "description" : "MongoDB 是一个 Nosql 数据库",
... "author" : "编程帮",
... "url" : "http://www.biancheng.net/mongodb/index.html",
... "likes" : 996
... }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 更新成功后您可以使用 find() 方法来查看更新后的数据。
 
> db.course.find().pretty()
{
        "_id" : ObjectId("603209d8e492ab9be9450304"),
        "title" : "MongoDB教程",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "author" : "编程帮",
        "url" : "http://www.biancheng.net/mongodb/index.html",
        "likes" : 996
}
{
        "_id" : ObjectId("603209d8e492ab9be9450305"),
        "title" : "HTML教程",
        "author" : "编程帮",
        "url" : "http://www.biancheng.com/html/index.html"
}
{
        "_id" : ObjectId("603209d8e492ab9be9450306"),
        "title" : "C#教程",
        "author" : "编程帮",
        "url" : "http://www.biancheng.com/csharp/index.html"
}