0

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

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

我想删除以下所有variants内容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)

关于如何解决这个问题的任何想法?

4

1 回答 1

0

不清楚您在这里处理的是一两条记录;我假设了两个。不要使用update()- 它已被弃用 - 使用update_one()or 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
                }
            ]
        }
    ]
}
于 2021-04-05T18:57:01.323 回答