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

270
Views
MongoDB query for adding to array if not present

I am new to MongoDB and want to know if there is any way to add an embedded document to an array if it is not present.

Let's say I have a collection called products:

{
    _id: "123",
    name: "Hair-Dryer",
    locations: [{
            code: "MA",
            name: "Massachusetts"
        },
        {
            code: "IL",
            name: "illinois"
        }
    ]
}, {
    _id: "456",
    name: "Toaster",
    locations: [{
        code: "MA",
        name: "Massachusetts"
    }, ]
}

Now lets say I want to add :

{
        code: "IL",
        name: "illinois"
}

To only those documents which don't have them. Note that, I don't know which documents have my required data or which don't have them. I need to find that out.

How can I write a query like this in MongoDB ?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

Try this:

db.locations.updateMany({}, {
    $addToSet: {
        locations: {
            code: "IL",
            name: "illinois"
        }
    }
});
over 4 years ago · Santiago Trujillo 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!