1

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Works perfectly. I knew that there should be some trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.