更多更新运算符

更新文档时,你可以使用除 $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.