2020-04-29

MongoDB 更新資料

MongoDB 更新資料

承上篇 MongoDB 新增資料,延用相同的 db 和 collections。

官方的文件說明

使用 mongo shell 操作,更新單筆資料使用 updateOne():

> db.inventory.updateOne( ... { ... item: 'notebook2' ... }, { ... $set: {qty: 30}, ... $currentDate: { lastModified: true } ... }) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

第一個參數為條件限定,可以使用 $lt 等運算子。 第二個參數的 $set 為所要變更的設定值;$currentDate 為要設定為當下時間的屬性。

更新多筆使用 updateMany():

> db.inventory.updateMany( ... { qty: { $lte: 30 } }, ... { ... $set: { 'size.uom': "in" }, ... $rename: { qty: 'quantity' }, ... $unset: { status: '' }, ... $currentDate: { lastModified: true } ... } ... ) { "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

$rename 為變更欄位( 屬性)名稱;$unset 刪除欄位。

replaceOne() 用來取代某個 document:

> db.inventory.replaceOne( ... { item: /notebook/ }, ... { 'hello': 'my-test' } ... ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

replaceOne() 的第一個參數通常會使用 _id 或不會重複的欄位來篩選資料。

沒有留言:

FB 留言