MongoDB 中的 update() 與 save() 方法都能用于更新集合中的文檔。update() 方法更新已有文檔中的值,而 save() 方法則是用傳入該方法的文檔來替換已有文檔。
update() 方法更新已有文檔中的值。
update() 方法基本格式如下:
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
假如 mycol 集合中有下列數(shù)據(jù):
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
下面的例子將把文檔原標(biāo)題 'MongoDB Overview' 替換為新的標(biāo)題 'New MongoDB Tutorial'。
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>
MongoDB 默認(rèn)只更新單個(gè)文檔,要想更新多個(gè)文檔,需要把參數(shù) multi 設(shè)為 true。
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}},{multi:true})
save() 方法利用傳入該方法的文檔來替換已有文檔。
save() 方法基本語法格式如下:
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
下例用 _id 為 '5983548781331adf45ec7' 的文檔代替原有文檔。
>db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point New Topic", "by":"Tutorials Point"
}
)
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic", "by":"Tutorials Point"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>