Let's say I have a collection that looks like this (essentially a double-nested array holding objects):
{
'customer': 'bob',
'products': [
{
'id': 5,
'variants': [
{'name': 'blue',
'id': 23},
{'name': 'orange',
'id': 13},
{'name': 'green',
'id': 53},
]
}
]
},
{
'customer': 'dylan',
'products': [
{
'id': 5,
'variants': [
{'name': 'blue',
'id': 23},
{'name': 'green',
'id': 53},
]
}
]
}
I would like to remove all variants whose id is in the following: [23, 53] for only bob
{
'customer': 'bob',
'products': [
{
'id': 5,
'variants': [
{'name': 'orange',
'id': 13},
]
}
]
},
{
'customer': 'dylan',
'products': [
{
'id': 5,
'variants': [
{'name': 'blue',
'id': 23},
{'name': 'green',
'id': 53},
]
}
]
}
I have the following, however it also removes all variants for dylan:
db.update({'$and': [{'user': 'bob'}, {'products': {'$elemMatch': {'id': 5}}}]}, {'$pull': {'products.$[].variants': {'id': {'$in': [23, 53]}}}}, False, True)
Any ideas on how to approach this?
It's not clear if you are dealing with one or two records here; I've assumed two. Don't use
update()- it's deprected - useupdate_one()orupdate_many(); and you're querying on auserfield that doesn't exist.Given all that, try:
Full example:
prints: