在mongodb和nodejs中减少类型为number的字段 [英] Decrementing a field of type number in mongodb and nodejs
本文介绍了在mongodb和nodejs中减少类型为number的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习mongodb.我有一个名为 item 的集合,该集合具有类型为Number的字段 piecesLeft
,我想在用户订购此特定项目时减少此字段的值.有帮助吗?
I'm learning mongodb.
I have a collection called item which has a field piecesLeft
of a type Number, and I want to decrement this field value when a user orders this particular item. Any help?
推荐答案
使用 $ inc 运算符.
db.yourcollection.update({ /* find options */ }, { $inc: {piecesLeft : -1 } });
已更新:
db.yourcollection.update({
_id: '572f16440a0dbb1e0cc02201', // Find updated item e.g. by _id
piecesLeft: { $gt: 0 } // Update only if piecesLeft > 0
}, {
$inc: {
piecesLeft: -1 // Increment by -1
}
});
这篇关于在mongodb和nodejs中减少类型为number的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文