[英]How do u increment one field every time and the other only if it's greater than a certain number with multi true ?
The following code decrements class_number
just fine, but not number_of_classes
because of the $gt
operator. 下面的代码递减
class_number
就好了,但不是number_of_classes
因以$gt
运营商。
posts.update({ 'title':doc.title, 'author':doc.author, 'class_number':{ '$gt': doc.class_number } },
{ '$inc': { 'number_of_classes':-1 , 'class_number':-1} },
{ multi: true }, function(err, dox){....
I need to decrement number_of_classes
once every time, but only each class_number
above a certain value. 我需要每次减少
number_of_classes
一次,但只有每个class_number
高于某个值。 Is there a way to do this in one statment? 有没有一种方法可以做到这一点?
No there is no way to "conditionally" update one field and not another, just as there is no way to "reference" an existing value of a field in a document during an update statement. 就像无法在更新语句期间“引用”文档中某个字段的现有值一样,没有办法“有条件地”更新一个字段,而不能“有条件地”更新另一个字段。 Much as your current statement provides, you can only perform the "conditions" on the query that you pass to the update.
就像您当前的语句所提供的一样,您只能对传递给更新的查询执行“条件”。
So if you are trying to hit a "floor" of 0 then your "safe" method is in two operations: 因此,如果您尝试将“底数”设置为0,则“安全”方法有两种操作:
db.collection.update(
{ "title":doc.title, "author":doc.author },
{ "$inc": "number_of_classes": -1 }
)
db.collection.update(
{
"title":doc.title,
"author":doc.author,
"$and": [
{ "class_number": { "$gt": 0 } },
{ "class_number": { "$gt": doc.class_number } }
]
},
{ "$inc": "class_number": -1 }
)
Or however that logic works for you in actual updates. 或者,该逻辑在实际更新中对您有用。
In future versions ( as of writing ) you can "batch" these updates into a single request, but they actually are still two operations, even though sent to the server only once. 在将来的版本中(撰写本文时),您可以将这些更新“批处理”到单个请求中,但是,即使仅发送到服务器一次,它们实际上仍然是两个操作。
I do somehow suspect that due to the way you are writing this statement that you are actually trying to solve some kind of "allocation" problem. 我确实怀疑由于您编写此语句的方式,您实际上正在尝试解决某种“分配”问题。 And that would be a different question to the way you are asking this here.
这与您在此处提出问题的方式将是一个不同的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.