Daria_N_A
(Daria N/A)
August 15, 2024, 12:32pm
1
I currently have a query, that filters elements of array and sets a field value for them.
Schedule.collection.updateMany(
{ },
{
$set: { 'objectName.$[elem].fieldName': 'value' }
},
{
arrayFilters: [ <filters here>]
}
);
That works perfectly. But now I need just to remove that element at all. I’ve checked unset and pull options, but I probably don’t fully understand the way to use them. I’m looking for a change like
$set: { 'availability.$[elem].status': 'past' } -> $objectName: { 'availability.$[elem] }
Joel_Lord
(Joel Lord)
August 19, 2024, 11:51am
2
Hi @Daria_N_A , and welcome to the forums!
$unset
should work for this. I tried this very simple example, and it worked for me.
First, add some data to your collection:
db.schedule.insertOne({sports: [{name: "running", completed: true}, {name: "swimming", completed: false}]});
You should have an element that looks like this:
{
"_id": {
"$oid": "66c3313298a302c33b5c6922"
},
"sports": [
{
"name": "running",
"completed": true
},
{
"name": "swimming",
"completed": false
}
]
}
Then, use the $unset
operator with the arrayFilters
as you did:
db.schedule.updateMany(
{},
{$unset: {"sports.$[elem].completed": ""}},
{arrayFilters: [ {"elem.completed": true} ]}
);
Your document should now look like this:
{
"_id": {
"$oid": "66c3313298a302c33b5c6922"
},
"sports": [
{
"name": "running"
},
{
"name": "swimming",
"completed": false
}
]
}
I hope this helps!
-Joel
1 Like
Daria_N_A
(Daria N/A)
August 21, 2024, 9:57pm
3
Thanks! I haven’t tried this solution, got this one working instead of set (and array filters removed):
$pull: {
objectName: {
rephrased filters here
}
}
system
(system)
Closed
August 26, 2024, 9:57pm
4
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.