Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!