[英]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.