Jimmy A. León
Jimmy A. León

Reputation: 561

Update with conditional Mongodb

I'm updating a value inside an array. But, I want that the update validates that the value cannot be less than zero.

{
  _id: ObjectId(),
  items: [
    {
        _id: ObjectId(),
        stock: 5
    }
  ]
}

In this case, if I want to decrease stock in -6. I need that the query raise an exception or something similar.

I was trying with two queries. One to know the actual value and then if the subtraction was > 0, I did the update.

Is there a way to make this in one query?

Upvotes: 1

Views: 227

Answers (1)

Sede
Sede

Reputation: 61273

You can take advantage of the fact that ObjectId is unique in for each element in the array and use the $ positional update operator to do this beautifully

from bson.objectid import ObjectId

collection.update_one(
    {"items": {
        "$elemMatch": {
            "_id" : ObjectId("58ccc8c2dbe8051261b38e58"), 
            "stock": {"$gt": 0 }
        }
    }}, 
    {"$inc": {"items.$.stock": -6 }}
)

Upvotes: 1

Related Questions