mongodb的update()
和save()
方法用于将集合中的文档更新。update()
方法更新现有文档中的值,而save()
方法使用save()
方法中传递的文档数据替换现有文档。
update()
方法更新现有文档中的值。
语法
update()
方法的基本语法如下 -
> db.collection_name.update(selection_criteria, updated_data)
示例
考虑mycol
集合具有以下数据 -
> db.mycol.find({}, {'_id':1, 'title':1})
{ "_id" : 100, "title" : "mongodb overview" }
{ "_id" : 101, "title" : "mongodb guide" }
{ "_id" : 102, "title" : "nosql database" }
{ "_id" : 104, "title" : "python quick guide" }
>
以下示例将为标题为“mongodb overview
”的文档设置为“new update mongodb overview
”。
> db.mycol.find({'title':'mongodb overview'},{'_id':1, 'title':1})
{ "_id" : 100, "title" : "mongodb overview" }
> # 更新操作
> db.mycol.update({'title':'mongodb overview'},{$set:{'title':'new update mongodb overview'}})
writeresult({ "nmatched" : 1, "nupserted" : 0, "nmodified" : 1 })
> # 查询更新后的结果 -
> db.mycol.find({'_id':100},{'_id':1, 'title':1})
{ "_id" : 100, "title" : "new update mongodb overview" }
>
默认情况下,mongodb只会更新一个文档。要更新多个文档,需要将参数’multi
‘设置为true
。
>db.mycol.update({'title':'mongodb overview'},
{$set:{'title':'new update mongodb overview'}},{multi:true})
save()
方法使用save()
方法中传递的文档数据替换现有文档。
语法
mongodb save()
方法的基本语法如下所示:
>db.collection_name.save({_id:objectid(),new_data})
以下示例将_id
为 100
的文档使用新的文档替换。
db.mycol.save(
{
"_id" : 100, "title":"update by save()method.", "by":"h3.com"
}
)
writeresult({ "nmatched" : 1, "nupserted" : 0, "nmodified" : 1 })
db.mycol.find({'_id':100}, {'_id':1, 'title':1})
{ "_id" : 100, "title" : "update by save()method." }