I have the following data structure:
{
_id: 599cfc236ed0d81c98007f66
site: 'abc'
timepoints [
{ timepoint: 0
testSites: [{testSite: 'abc', address: '123'},
{testSite: 'mno', address: '789'}],
},
{ timepoint: 2
testSites: [{testSite: 'abc', address: '123'}],
},
{ timepoint: 4
testSites: [{testSite: 'mno', address: '789'}],
},
]
}
I have read through the MongoDB update operator for $pull, but it does not have an example of pulling a element from an array of an embedded/embedded document and I can't figure it out:
I would like to pull all elements whose site = 'abc' and whose testSite = 'abc', thus the result would be:
{
_id: 599cfc236ed0d81c98007f66
site: 'abc'
timepoints [
{ timepoint: 0
testSites: [{testSite: 'mno', address: '789'}],
},
{ timepoint: 2
testSites: [],
},
{ timepoint: 4
testSites: [{testSite: 'mno', address: '789'}],
},
]
}
I tried the following command, but it pulls all the timepoints documents and not the embedded documents within testSites:
$db->collection1->update(
['site' => 'abc'],
['$pull' => ['timepoints' => ['testSites' => ['$elemMatch' => ['testSite' => 'abc']]]]],
['multi' => true]);
UPDATE: I agree this is a duplicate question with an answer. I was just able to find the following:
So the command does pull the lower level element, but only from timepoint 0:
db.collection1.update({'site': 'abc',
'timepoints.testSites.testSite': 'abc'},
{'$pull': {'timepoints.$.testSites': {'testSite': 'abc'}}},
{'multi': true}
);
Why is the second occurrence in timepoint 2 not pulled?