PyMongo:从数组中提取一个对象



假设我有一个看起来像这样的集合(本质上是一个包含对象的双嵌套数组(:

{ 
'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},
]    
}
]
}

我想删除其id位于以下位置的所有variants:仅bob[23, 53]

{ 
'customer': 'bob',
'products': [
{
'id': 5,
'variants': [ 
{'name': 'orange',
'id': 13}, 
]    
}
]
},
{ 
'customer': 'dylan',
'products': [
{
'id': 5,
'variants': [
{'name': 'blue',
'id': 23},
{'name': 'green',
'id': 53},
]    
}
]
}

我有以下内容,但它也删除了dylan的所有变体:

db.update({'$and': [{'user': 'bob'}, {'products': {'$elemMatch': {'id': 5}}}]}, {'$pull': {'products.$[].variants': {'id': {'$in': [23, 53]}}}}, False, True)

关于如何处理这个问题,有什么想法吗?

这里不清楚您处理的是一条还是两条记录;我假设了两个。不要使用update()——这是弃用的——使用update_one()update_many();而您正在查询一个不存在的user字段。

考虑到这一切,试试:

db.mycollection.update_one({'customer': 'bob', 'products.variants.id': {'$in': [23, 53]}},
{'$pull': {'products.$.variants': {'id': {'$in': [23, 53]}}}})

完整示例:

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))

打印:

{
"customer": "bob",
"products": [
{
"id": 5,
"variants": [
{
"name": "orange",
"id": 13
}
]
}
]
}

相关内容

最新更新