Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

314
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda