I want to manage (append, remove, and update) documents within an array, and the array field is within a document within an array. I’m talking about the “notifications” array visible in the following sample document:
{
docId: "123",
outcomes: [
{
prizeId: "test",
notifications: [
{
action: "foo",
foreignKey: "abc"
}
]
}
]
}
Given these parameters provided by a client,
params = {
docId: "123",
prizeId: "test",
action: "foo",
}
I am able to select (find) the document with the following filter:
filter = {docId: params.docId, outcomes: {$elemMatch: {prizeId: params.prizeId}}}
db.getCollection('collection-name').find(filter)
I am not able to modify the document. For “remove”, I tried the following:
update = {
$pull: {
"outcomes.$.notifications": {
$elemMatch: {
action: params.action
}
}
}
}
db.getCollection('collection-name').updateOne(filter, update)
As well as
update = {
$pull: {
"outcomes.$[outcome].notifications": {
$elemMatch: {
action: params.action
}
}
}
}
options = {
arrayFilters: [
{ "outcome.prizeId" : params.prizeId },
// { "notification.action" : action },
]
}
db.getCollection('collection-name').updateOne(filter, update, options)
I’m suprised I cannot find examples in the documentation that deal with removing an array item from an array nested within a document within an array.
UPDATE: Actually I did find an example showing how to remove an item from a nested array. Unfortunately, I believe I am doing the same technique for my data, but the results are not the same. The main difference I can see is that I’m using updateOne
and the example uses updateMany
.
UPDATE 2: I believe the example does not do what I need. It updates multiple documents, and potentially multiple (outer) array items, and the syntax I need should constrain to updating one (outer) array item.