Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda