使用$inc操作符将一个字段的值增加或者减少的格式是:

    1. { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

    $inc操作符接收正的和负的值
    如果指定的字段不存在则$inc操作符创建这个字段并且设置这个字段的值为指定的在值;
    使用$inc操作符的字段的值如果值为null则将会报异常;
    $inc操作符是原子性的在单个文档中;

    1. {
    2. _id: 1,
    3. sku: "abc123",
    4. quantity: 10,
    5. metrics: {
    6. orders: 2,
    7. ratings: 3.5
    8. }
    9. }

    $inc操作符将quantity减2,metrics.orders内嵌文档字段加1

    1. db.products.update(
    2. { "_id": 1},
    3. { $inc: { quantity: -2, "metrics.orders": 1 } }
    4. )
    1. {
    2. "_id" : 1,
    3. "sku" : "abc123",
    4. "quantity" : 8,
    5. "metrics" : {
    6. "orders" : 3,
    7. "ratings" : 3.5
    8. }
    9. }