skip to Main Content

I have a document like this

    {
      "_id": ObjectId("626f942bb092f78afd9dad9d"),
      "item_id": "external _id222",
      "metadata": {
        "item_name": "abc",
        "quantity": 123,
        "state": null
      },
    }

What I would like to do is, $inc i.e. increment the count of quantity and then update the state to SOLD, if quantity equals 124. I can do this by 2 queries, update quantity, do an if-else check and then update state. Is there a way to do this in one single query by update()? (preferably without aggregation)

2

Answers


  1. You can do this way

    1. Check if quantity is 123
    2. Then increment quantity and set state to SOLD

    playground

    db.collection.update({
      "metadata.quantity": 123
    },
    {
      "$inc": {
        "metadata.quantity": 1
      },
      "$set": {
        "metadata.state": "SOLD"
      }
    },
    {
      "multi": false,
      "upsert": false
    })
    

    Here, the trick is that you need to check the value which is before $inc operation.

    Login or Signup to reply.
  2. With MongoDB v4.2+, you can do this with a single update with an aggregation pipeline to achieve atomic behaviour. Use $add to do the increment and $cond to check for quantity = 123

    db.collection.update({
      "item_id": "external _id222"
    },
    [
      {
        $set: {
          "metadata.quantity": {
            $add: [
              "$metadata.quantity",
              1
            ]
          }
        }
      },
      {
        $set: {
          "metadata.state": {
            $cond: {
              if: {
                $eq: [
                  "$metadata.quantity",
                  124
                ]
              },
              then: "SOLID",
              else: "$metadata.state"
            }
          }
        }
      }
    ],
    {
      multi: true
    })
    

    Here is the Mongo playground for your reference.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search