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

204
Visualizações
Mongodb, use selected document value to update field in same document using single operation

Lets say you are making a simply todo app and you have a structure that looks like this:

{
[userId]: {
  nextTaskId:3,
  tasks: {
    1: "take out the trash",
    2: "pick up milk"
  }
}

When adding a task, I'd like to create a new record using the the nextTaskId and also increment it. I have seen other examples using a aggregation function like $concat or the like, but that doesn't fit my usecase.

I'd like to be able to reference the field in my update, something like:

db.tasks.updateOne({_id:5}, {$inc:{nextId:1}, $set: {"tasks.$nextId":{"new task" }}})

the field does get incremented, however the tasks key is not 3, but $nextId and I also tried using it as a value, as in:

db.tasks.updateOne({_id:5}, {$inc:{nextId:1}, $set: {"tasks.3":{"$nextId" }}})

that doesn't work either. of course, I could do this by making 2 individual operations, one to get the next id and increment it, and another to create the new task record, but i'm hoping to do it with a single operation.

Any ideas?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use update with aggregation pipeline to achieve the behaviour in one single update statement. Use $objectToArray and $arrayToObject to manipulate the tasks array.

db.collection.update({
  _id: 5
},
[
  {
    "$addFields": {
      "tasks": {
        "$objectToArray": "$tasks"
      }
    }
  },
  {
    "$addFields": {
      "nextTaskId": {
        $add: [
          "$nextTaskId",
          1
        ]
      },
      tasks: {
        "$concatArrays": [
          "$tasks",
          [
            {
              k: {
                $toString: "$nextTaskId"
              },
              // your input for the new task
              v: "next task"
            }
          ]
        ]
      }
    }
  },
  {
    "$addFields": {
      "tasks": {
        "$arrayToObject": "$tasks"
      }
    }
  }
])

Here is the Mongo playground for your reference.

over 4 years ago · Santiago Trujillo 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