簡體   English   中英

PyMongo:在 arrays 數組中拉取一個 object

[英]PyMongo: Pull an object in an array of arrays

假設我有一個看起來像這樣的集合(本質上是一個包含對象的雙嵌套數組):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM