更新操作符

$set是默认行为,通常省略不写;在众触,通常是更新x里的详细信息,因此x.也默认不写。
比如把{ $set: { "x.姓名": "张三", "x.年龄": 18 } }简写成{ 姓名: "张三", 年龄: 18 }
但如果要删除某些字段,如删除了年龄{ 姓名: "张三" },简写的话年龄将不会有变化(依旧存在),此时就应该把x字段作为整体更新:{ $set: { x: { 姓名: "张三" } } },这样x字段被整个替换了,也就没有年龄字段了。
更新y里的内容时y.是不能省略的。其它字段不能直接更新。

字段操作符

$unset

从文档中删除指定的字段。
Removes the specified field from a document.
{ $unset: { "x.qty": "", "x.stock": "" } } :删除数量和库存字段

$inc

将字段的值增加指定的数量。
Increments the value of the field by the specified amount.
{ $inc: { "x.order": 1, "x.stock": -2 } } :订单加1,库存减2

$mul

将字段的值乘以指定的数量。
Multiplies the value of the field by the specified amount.
{ $mul: { "x.price": 0.8 } } :价格打8折

$rename

字段重命名。
{ $rename: { "x.nme": "x.name" } }

数组操作符

$push

将项目添加到数组。
{ $push: { "x.tags": "电器" } } :添加一个标签
{ $push: { "x.arr": { a: 1 } } } :往数组x.arr插入对象
{ $push: { "x.scores": { $each: [90, 92, 85] } } } :往数组x.scores添加多项
{ $push: { y: { $position: 0, $each: [{ event: "签到", amount: 1 }] } } :添加数组
y的队首

$addToSet

同$push,但只有当数组中不存在待插入的数据项时才执行,即不插入已存在的数据项

$pop

删除数组的最后一项或第一项。
{ $pop: { "x.scores": 1, "x.books": -1 } } :删除scores数组中的最后一个元素和删除books数组中的第一个元素

$pull

删除与指定查询匹配的所有数组元素。
{ $pull: { "x.votes": { $gt: 6 } } } 移除votes数组中大于6的数字
{ $pull: { "x.results": { item: "B", score: 8 } } } 移除results数组中item == "B" && score == 8的对象

$pullAll

从数组中删除所有匹配的值。
{ $pullAll: { "x.scores": [0, 5] } } 移除scores数组中的所有0和5

数组修饰符

$each

修饰$push运算符以附加多个项以进行数组更新。

$position

修饰$push运算符以指定要添加元素的数组中的位置。

$slice

修饰$push运算符以限制更新数组的大小。
{ $push: { "y.arr": { $each: [{ name: "Ken", score: 85 }], $slice: -10 } } } 插入新元素后截取数组的后10位

$sort

修饰$push运算符以对存储在数组中的文档重新排序。
{ $push: { "y.arr": { $each: [], $sort: { score: -1 }, $slice: 10 } } } 按成绩降序排序并截取数组的前10位

更多更新操作请参照官网文档

由众触低代码平台生成和驱动