$set
是默认行为,通常省略不写;在众触,通常是更新x
里的详细信息,因此x.
也默认不写。
比如把{ $set: { "x.姓名": "张三", "x.年龄": 18 } }
简写成{ 姓名: "张三", 年龄: 18 }
更新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折 |
数组操作符
$push | 将项目添加到数组。 { $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 的队首 |
$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位 |
更多更新操作请参照官网文档