更多更新運算子

更新文件時,你可以使用除 $set 之外的其他運算子。$push 運算子允許你將值推送到陣列中,在這種情況下,我們將向 nicknames 陣列新增新的暱稱。

db.people.update({name: 'Tom'}, {$push: {nicknames: 'Tommy'}})
// This adds the string 'Tommy' into the nicknames array in Tom's document.

$pull 運算子與 $push 相反,你可以從陣列中提取特定項。

db.people.update({name: 'Tom'}, {$pull: {nicknames: 'Tommy'}})
// This removes the string 'Tommy' from the nicknames array in Tom's document.

$pop 運算子允許你從陣列中刪除第一個或最後一個值。假設 Tom 的文件中有一個名為 siblings 的屬性,其值為 ['Marie', 'Bob', 'Kevin', 'Alex']

db.people.update({name: 'Tom'}, {$pop: {siblings: -1}})
// This will remove the first value from the siblings array, which is 'Marie' in this case.

db.people.update({name: 'Tom'}, {$pop: {siblings: 1}})
// This will remove the last value from the siblings array, which is 'Alex' in this case.