ignareyesa
ignareyesa

Reputation: 25

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!

Upvotes: 0

Views: 43

Answers (1)

Erik
Erik

Reputation: 485

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

Upvotes: 1

Related Questions