Python PyMongo:从数组中提取对象
假设我有一个这样的集合(本质上是一个包含对象的双嵌套数组): 我想删除所有Python PyMongo:从数组中提取对象,python,mongodb,pymongo,pymongo-3.x,pymongo-2.x,Python,Mongodb,Pymongo,Pymongo 3.x,Pymongo 2.x,假设我有一个这样的集合(本质上是一个包含对象的双嵌套数组): 我想删除所有变体,其id如下:[23,53]仅用于bob { 'customer': 'bob', 'products': [ { 'id': 5, 'variants': [ {'name': 'orange', 'id': 13}, ] } ] }, { 'customer': 'dylan', 'products': [
变体
,其id
如下:[23,53]
仅用于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},
]
}
]
}
我有以下内容,但是它也删除了dylan的所有变体:
db.update({'$and':[{'user':'bob'},{'products':{'elemMatch':{'id':5}}}},{'$pull':{'products.$[].variants':{'id':{'in':[23,53]}},False,True)
关于如何处理这个问题有什么想法吗?不清楚您在这里处理的是一个还是两个记录;我假设有两个。不要使用
update()
-这是不推荐的-使用update\u one()
或update\u 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
}
]
}
]
}
这回答了你的问题吗?
{
"customer": "bob",
"products": [
{
"id": 5,
"variants": [
{
"name": "orange",
"id": 13
}
]
}
]
}