基于过滤器的数组中的(py)mongo BulkUpdate元素

时间:2019-10-10 07:50:36

标签: python mongodb pymongo

我正在尝试为批量更新创建许多更新操作。

我试图通过array filter在数组中选择一个元素(字典),但是要比该字段更新(或更精确地说是向上插入)该元素上的另一个字段(在下面的示例new_field中)数组过滤器将应用于。

简而言之:

  • 具有字典数组
  • 通过key_1选择数组中的元素
  • 在先前选择的元素上更新key_2:value_2

我目前正在尝试使用一个(测试)记录进行这项工作。

(测试)记录如下:

{
  '_id': '001d1a70fdc77812053d',
  'images': {
    'photos': [{'id':'jxptm90a'}]
  },
  ...
}

更新操作如下:

update_operation = pymongo.UpdateOne(
    filter={'_id': '001d1a70fdc77812053d'},
    update={
        '$currentDate': {'oplog_skip': True},
        '$set': { "images.photos.$[new_field]": 2 },

    },
    upsert=False,
    array_filters=[ { 'id': 'jxptm90a' }]
)

但是,执行如下命令:

  db.collection.bulk_write([update_operation])

导致以下错误:

{'writeErrors': [{'index': 0, 'code': 2, 'errmsg': "No array filter found for identifier 'test' in path 'images.photos.$[test]'", 'op': SON([('q', {'_id': '001d1a70fdc77812053d'}), ('u', {'$currentDate': {'oplog_skip': True}, '$set': {'images.photos.$[test]': 2}}), ('multi', False), ('upsert', False), ('arrayFilters', [{'id': 'jxptm90a'}])])}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []}
---------------------------------------------------------------------------
BulkWriteError                            Traceback (most recent call last)
<ipython-input-74-d31fe774222f> in <module>
      5 
      6     try:
----> 7         db.collection.bulk_write([update])
      8     except _pymongo.errors.BulkWriteError as bwe:
      9         print(bwe.details)

~/anaconda3/envs/py363/lib/python3.6/site-packages/pymongo/collection.py in bulk_write(self, requests, ordered, bypass_document_validation, session)
    495 
    496         write_concern = self._write_concern_for(session)
--> 497         bulk_api_result = blk.execute(write_concern, session)
    498         if bulk_api_result is not None:
    499             return BulkWriteResult(bulk_api_result, True)

~/anaconda3/envs/py363/lib/python3.6/site-packages/pymongo/bulk.py in execute(self, write_concern, session)
    511                 self.execute_no_results(sock_info, generator)
    512         else:
--> 513             return self.execute_command(generator, write_concern, session)
    514 
    515 

~/anaconda3/envs/py363/lib/python3.6/site-packages/pymongo/bulk.py in execute_command(self, generator, write_concern, session)
    339 
    340         if full_result["writeErrors"] or full_result["writeConcernErrors"]:
--> 341             _raise_bulk_write_error(full_result)
    342         return full_result
    343 

~/anaconda3/envs/py363/lib/python3.6/site-packages/pymongo/bulk.py in _raise_bulk_write_error(full_result)
    138         full_result["writeErrors"].sort(
    139             key=lambda error: error["index"])
--> 140     raise BulkWriteError(full_result)
    141 
    142 

BulkWriteError: batch op errors occurred

1 个答案:

答案 0 :(得分:1)

过滤器标识符必须与$ set操作匹配;例如像这样:

update_operation = pymongo.UpdateOne(
    filter={'_id': '001d1a70fdc77812053d'},
    update={
        '$currentDate': {'oplog_skip': True},
        '$set': { "images.photos.$[id]": 2 },
    },
    upsert=False,
    array_filters=[ { 'id': 'jxptm90a' }]
)