Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!