Reputation: 1
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?
Upvotes: 0
Views: 305
Reputation: 8814
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 - use update_one()
or update_many()
; and you're querying on a user
field that doesn't exist.
Given all that, try:
db.mycollection.update_one({'customer': 'bob', 'products.variants.id': {'$in': [23, 53]}},
{'$pull': {'products.$.variants': {'id': {'$in': [23, 53]}}}})
Full example:
from pymongo import MongoClient
import json
db = MongoClient()['mydatabase']
db.mycollection.insert_many([
{
'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},
]
}
]
}]
)
db.mycollection.update_one({'customer': 'bob', 'products.variants.id': {'$in': [23, 53]}},
{'$pull': {'products.$.variants': {'id': {'$in': [23, 53]}}}})
for item in db.mycollection.find({'customer': 'bob'}, {'_id': 0}):
print(json.dumps(item, indent=4))
prints:
{
"customer": "bob",
"products": [
{
"id": 5,
"variants": [
{
"name": "orange",
"id": 13
}
]
}
]
}
Upvotes: 0