update

UK[ˌʌpˈdeɪt] US[ʌpˈdet]

vt. Update, modernize; correct, amend

n. Modernize; Updated information; updated behavior or instances

MongoDB update() method syntax

Function: update() method to update documents in the collection

Syntax: db.collection.update(<query>,<update> , {upsert: <boolean>,multi: <boolean>,writeConcern: <document>})

##Parameters: query: update query conditions, similar to sql behind where in the update query. update: the update object and some update operators (such as $, $inc...), etc., can also be understood as the upsert after set in the sql update query: optional, this parameter means that if there is no update Record, whether to insert objNew, true means insert, the default is false, not insert. multi: Optional, the default value of mongodb is false, and only the first record found is updated. If this parameter is true, all multiple records found according to the conditions will be updated. writeConcern: Optional, the level at which the exception is thrown.

MongoDB update() method example

我们在集合 col 中插入如下数据:

>db.col.insert({
    title: 'MongoDB 教程', 
    description: 'MongoDB 是一个 Nosql 数据库',
    by: 'php中文网',
    url: '//m.sbmmt.com',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})
接着我们通过 update() 方法来更新标题(title):

>db.col.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })   # 输出信息
> db.col.find().pretty()
{
        "_id" : ObjectId("56064f89ade2f21f36b03136"),
        "title" : "MongoDB",
        "description" : "MongoDB 是一个 Nosql 数据库",
        "by" : "php中文网",
        "url" : "//m.sbmmt.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
>
可以看到标题(title)由原来的 "MongoDB 教程" 更新为了 "MongoDB"。

以上语句只会修改第一条发现的文档,如果你要修改多条相同的文档,则需要设置 multi 参数为 true。

>db.col.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}},{multi:true})