无涯教程-MongoDB - 更新数据
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
MongoDB的 update()和 save()方法用于将文档更新为集合,update()方法更新现有文档值,而save()方法将现有文档替换为save()方法中传递的文档。
MongoDB Update()方法
update()方法更新现有文档中的值。
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
考虑到mycol集合具有以下数据。
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Learnfk Point Overview"}
以下示例将为标题为" MongoDB Overview"的文档设置新标题" 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":"Learnfk Point Overview"} >
默认情况下,MongoDB仅更新一个文档。要更新多个文档,您需要将参数" multi"设置为true。
>db.mycol.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Tutorial'}},{multi:true})
MongoDB Save()方法
save()方法将现有文档替换为save()方法中传递的新文档。
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
以下示例将文档替换为_id'5983548781331adf45ec5'。
>db.mycol.save( { "_id" : ObjectId(5983548781331adf45ec5), "title":"Learnfk Point New Topic", "by":"Learnfk Point" } ) >db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec5), "title":"Learnfk Point New Topic", "by":"Learnfk Point"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Learnfk Point Overview"} >
参考链接
https://www.learnfk.com/mongodb/mongodb-update-document.html
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |