简体   繁体   中英

Update field and $push to array in one query in MongoDB

I have this code:

db.basket.update(
    {'_id': ObjectId(data['basket_id'])},
    {
        'total': round(total, 2),
        '$push': {
            products': {
                'prod_id': data['prod_id'],
                'price': price,
                'amount': data['amount']
            }
        }
    }
)

Running this query gives me an error:

uncaught exception: field names cannot start with $ [$push]

Is it possible to update field in database object and push new object into array?

You needed to use $set for your single value update. Otherwise this is attempting to mix the form of update with a plain object and a "update" operator. MongoDB thinks this is just a plain object update and thus tells you that "$push" is illegal for a field name:

db.basket.update(
    {'_id': ObjectId(data['basket_id'])},
    {
        '$set': { 'total': round(total, 2) },
        '$push': {
            products': {
                'prod_id': data['prod_id'],
                'price': price,
                'amount': data['amount']
            }
        }
    }
)

So using the correct operator here let's MongoDB know what you are trying to do and processes it correctly. Other update operators work in the same way. Only where all together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM