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

186
Views
Conditional array update MongoDB

I have a collection like this one:

{
"citizen":[
  {
    "country":"ITA",
    "language":"Italian"
  },
  {
    "country":"UK",
    "language":"English"
  },
  {
    "country":"CANADA",
    "language":"French"
  }]
}

I'm trying to update the collection but with a certain condition. I need to update remove an element of the array citizen if the value in the field country is longer than 3 characters.

I got that to remove an element i have to use $pull, to check the size of a string I have to use $strLenCP and $gt is greater than, but I'm struggling to put them together.

The result of the update should be:

{
"citizen":[
  {
    "country":"ITA",
    "language":"Italian"
  },
  {
    "country":"UK",
    "language":"English"
  }]
}

Any suggestions?

EDIT: with the collection, as it is, the command:

db.getCollection('COLLECTION').update(  { }, {  $pull:  {"citizen": {"country": /^[\s\S]{4,}$/}}}, { multi: true })

works perfectly. I tried it on another collection as this one:

{
"cittadino":{
  "citizen":[
    {
      "country":"ITA",
      "language":"Italian"
    },
    {
      "country":"UK",
      "language":"English"
    },
    {
      "country":"CANADA",
      "language":"French"
    }]
  }
}

and it doesn't update anymore. What should i do?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You're on the right path:

db.getCollection('COLLECTION').update(  { }, {  $pull:  {"citizen": {"country": /^[\s\S]{4,}$/}}}, { multi: true })

$pull operator takes a value or a condition. You need to use this to filter the array based on the "country" property

EDIT:

Use the dot-notation to access the nested document

db.getCollection('COLLECTION').update(  { }, {  $pull:  {"cittadino.citizen": {"country": /^[\s\S]{4,}$/}}}, { multi: true })
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!