【Mongoose】$inc的使用

来源:互联网 发布:mac涂层脱落几年包换屏 编辑:程序博客网 时间:2024/04/24 23:37

mongoose官网文档:
https://docs.mongodb.com/manual/reference/operator/update-field/
1.作用

Increments the value of the field by the specified amount.

用来增加指定字段的数量

2.用法
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

3.举例

{  _id: 1,  sku: "abc123",  quantity: 10,  metrics: {    orders: 2,    ratings: 3.5  }}
db.products.update(   { sku: "abc123" },   { $inc: { quantity: -2, "metrics.orders": 1 } }//-2表示每次减21表示每次加1)

结果为

{   "_id" : 1,   "sku" : "abc123",   "quantity" : 8,   "metrics" : {      "orders" : 3,      "ratings" : 3.5   }}

4.注意事项

1.若输入的字段不存在,$inc则会创建该字段

2.若把$inc用在了空字段会报错。

原创粉丝点击