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

279
Views
MongoDB remove duplicates from a nested array

I have a users collection with the following structure:

[
  {
    name: "xxx",
    labels: [
      {
        category: "Language",
        values: ["English", "Spanish"],
      },
      {
        category: "Hobby",
        values: ["Read", "Cook", "Read"],
      },
    ]
  },
  {
    name: "yyy",
    labels: [
      {
        category: "Language",
        values: ["English", "English"],
      },
      {
        category: "Hobby",
        values: ["Read", "Play", "Play"],
      },
    ]
  },
]

I want to delete all duplicates from values array, so the result would be:

[
  {
    name: "xxx",
    labels: [
      {
        category: "Language",
        values: ["English", "Spanish"],
      },
      {
        category: "Hobby",
        values: ["Read", "Cook"],
      },
    ]
  },
  {
    name: "yyy",
    labels: [
      {
        category: "Language",
        values: ["English"],
      },
      {
        category: "Hobby",
        values: ["Read", "Play"],
      },
    ]
  },
]

I tried to use setUnion and setIntersection, but I didn't know what is the right why to use them with a nested array.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

For Mongo version 4.2+ you can use pipeline updates for this, like so:

db.collection.updateMany(
{},
[
  {
    "$set": {
      labels: {
        $map: {
          input: "$labels",
          in: {
            $mergeObjects: [
              "$$this",
              {
                values: {
                  $setUnion: "$$this.values"
                }
              }
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

For older Mongo versions you'll have to read each document into memory and do this in code, then update each document separately.

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!