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?
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 })