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

313
Views
How to increment value in multiple fields and multiple documents in mongodb in one query

I have an object which is representing a lesson

 {
    "_id": "62ad8ac4a5523541d78df217",
    "lessonID": "35d02fc5-94dd-48e7-a315-7dcea6ac6806",
    "teachers": [
        "629232d2fc8fa8646b21cf3d"
    ],
    "students": [
        "62924d0a6055ad4d2533577b"
    ],
    "subject": "English",
    "start": 1655515800000,
    "end": 1655517600000,
    "roomNumber": "3",
    "venue": "Elmwood Park",
    "attendance": [
        "62924d0a6055ad4d2533577b"
    ],
    "paid": false,
    "__v": 0
},       
           

what i'm trying to do is to find all documents with the same "lessonID" and update "start" and "end" (timestamps).

I'd like to increment or decrease values by a certain amount on every document

I've been sitting on it for a while and I thought about doing this:

  • finding all documents that match my query
  • deleting all found documents
  • mapping through the array
  • inserting the mapped array of documents

it sounds extremely inefficient tho (and it causes duplicate or loss of data if any of the steps fail)... there must be a better way to do that.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As @Gibbs suggested, simply use $inc:

db.collection.update({
  "lessonID": "35d02fc5-94dd-48e7-a315-7dcea6ac6806"
},
{
  $inc: {start: amountStartInc, end: amountEndInc}
})

See how it works on the playground example

about 4 years ago · Juan Pablo Isaza 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!