简体   繁体   中英

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.

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
  • $sum - To increase the current value of the counter by 1 if the condition is true
db.collection.update({
  "key": 1
},
[
  {
    "$set": {
      "counter": {
        $cond: {
          if: {
            $lt: [
              "$counter",
              500
            ]
          },
          then: {
            $sum: [
              "$counter",
              1
            ]
          },
          else: 0
        }
      }
    }
  }
],
{
  "multi": false,
  "upsert": false
})

Working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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