简体   繁体   English

mongodb 中的条件 findoneandupdate

[英]Conditional findoneandupdate in mongodb

I need to increment the counter field as long as it's less than 500 otherwise reset the counter to zero.我需要增加计数器字段,只要它小于 500,否则将计数器重置为零。

Here is my snippet:这是我的片段:

StudentInfo.findOneAndUpdate(
    { studId: SID },
    **{ $inc: { counter: 1 } },**
    (err, studInfo) => {
        if (err || !studInfo) {
            console.log(err);
        } else {
            console.log(${JSON.stringify(studInfo));
        }
    },
);

How can I do it in a single update call?如何在单个更新调用中做到这一点?

You can do it with Aggregation framework:您可以使用聚合框架来做到这一点:

  • $cond with $lt - To check if the current value of the counter is less than 500 $cond$lt - 检查计数器的当前值是否小于 500
  • $sum - To increase the current value of the counter by 1 if the condition is true $sum - 如果条件为真,将计数器的当前值加 1
db.collection.update({
  "key": 1
},
[
  {
    "$set": {
      "counter": {
        $cond: {
          if: {
            $lt: [
              "$counter",
              500
            ]
          },
          then: {
            $sum: [
              "$counter",
              1
            ]
          },
          else: 0
        }
      }
    }
  }
],
{
  "multi": false,
  "upsert": false
})

Working example工作示例

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM