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

117
Visualizações
addToSet mongoDB not adding if one value is repeated

I have the following collection in MongoDB

[
  {
    "acronym": "front",
    "references": [
      {
        "date": "2020-03-04",
        "value": "5.6"
      },
      {
        "date": "2020-03-05",
        "value": "6.3"
      }
    ]
  }
]

I want to use the function $addToSet in order to add new document into references. I know that it can be done with the following code:

db.collection.update({
  "acronym": "front"
},
{
  $addToSet: {
    "references": {
      "date": "2020-03-06",
      "value": "6"
    }
  }
})

And it will add the new document to the array references, so the result is the following:

[
  {
    "acronym": "front",
    "references": [
      {
        "date": "2020-03-04",
        "value": "5.6"
      },
      {
        "date": "2020-03-05",
        "value": "6.3"
      },
      {
        "date": "2020-03-06",
        "value": "6"
      }
    ]
  }
]

QUESTION: What I want to obtain is that in the case of adding a date that is already in the array, the update will no be produced.

Here is the playground: https://mongoplayground.net/p/DPER2RuROEs

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can add another qualifier to the update to prevent duplicated dates

db.collection.update({
  "acronym": "front",
  "references.date": {
    $ne: "2020-03-04"
  }
},
{
  $addToSet: {
    "references": {
      "date": "2020-03-04",
      "value": "6"
    }
  }
})

I got the solution from here

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