简体   繁体   English

在MongoDB中的一个查询中更新字段和$ push to array

[英]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. 您需要使用$set进行单值更新。 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: MongoDB认为这只是一个普通的对象更新,因此告诉你“$ push”对于字段名称是非法的:

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. 所以在这里使用正确的运算符让MongoDB知道你要做什么并正确处理它。 Other update operators work in the same way. 其他更新运算符以相同的方式工作。 Only where all together. 只有在一起的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将项目推送到数组并在 MongoDB 中获取该项目的索引,find_one_and_update pymongo 中的投影 - How to push an item to an array and get the index of that item in MongoDB, Projection in find_one_and_update pymongo Mongodb 基于数组字段查找查询 - Mongodb find query based on an array field $push 和 $set 在同一个更新查询中,条件为 $cond pymongo mongodb - $push and $set in same update query with condition $cond pymongo mongodb 更新与 mongodb 中的查询匹配的多个数组元素 - update multiple array elements matching a query in mongodb MongoDB使用$ push更新匹配条件的数组元素 - MongoDB update an array element matching a condition using $push 如何将一个数组字段的长度添加到 Mongodb 文档中的另一个字段中 - How to add length of one array field into another field in Mongodb document MongoDB | 基于一个字段逐条记录更新行 - MongoDB | Update rows record by record on basis of one field MongoDB:$Push 不更新文档 - MongoDB: $Push Does not Update Document 如何查询包含数组项之一的字符串字段? - How to query a string field contains one of array items? 在使用pymongo在mongodb中使用upsert将查询更新为true后,如何返回记录字段? - How to return field of record after update query with upsert as true in mongodb using pymongo?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM