【问题标题】:How to increment the value of each element in the array/list using pymongo?如何使用 pymongo 增加数组/列表中每个元素的值?
【发布时间】:2016-03-05 14:13:26
【问题描述】:

$inc in update 适用于一个数字 -

{
     _id:1,
    data:5
}

可以更新数据-

db.collection.update({}, {$inc:{data:10}}

数据是更新后的总和 -

{
     _id:1,
    data:15
}

但是,对于数字数组,我不能这样做 -

{
    _id:1,
    data:[1,2,3,4,5,6]
}

我需要类似的东西 -

db.collection.update({}, {$inc:{data:[1,1,1,1,1,1]}}

出现错误 -

"code" : 14,
"errmsg" : "Cannot increment with non-numeric argument: {pnl: [...]}"

这是我需要的结果 -

{
    _id:1,
    data:[2,3,4,5,6,7]
}

您能否建议我,我该如何实现?

【问题讨论】:

    标签: python mongodb mongodb-query pymongo


    【解决方案1】:

    您需要使用bulk API 并使用[] 运算符动态构建查询。

    >>> import pymongo
    >>> client = pymongo.MongoClient()
    >>> db = client.test
    >>> collection = db.collection
    >>> bulk = collection.initialize_ordered_bulk_op()
    >>> count = 0
    >>> for doc in collection.find({'data': {'$exists': True}}):
    ...     for index, value in enumerate(doc['data']):
    ...         inc = {}
    ...         inc['data.'+str(index)] = 1 
    ...         bulk.find({'_id': doc['_id']}).update_one({'$inc': inc})
    ...         count = count + 1
    ...     if count % 150 == 0:
    ...         bulk.execute() # Execute per 150 operations and  re-init
    ...         bulk = collection.initialize_ordered_bulk_op()
    ...
    >>> if count > 0:
    ...     bulk.execute() # clean up queues
    ...
    {'writeErrors': [], 'writeConcernErrors': [], 'upserted': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 6, 'nModified': 6, 'nRemoved': 0}
    >>> list(collection.find())
    [{'data': [2, 3, 4, 5, 6, 7], '_id': ObjectId('565dc8ec8ec4081174f6161a')}]
    >>>
    

    您也可以像这样在 shell 中执行此操作:

    var bulk = db.collection.initializeOrderedBulkOp();
    var count = 0;
    for doc in db.collection.find({ 'data': { '$exists': true } }):
        var data = doc.data;
        for (var index=0; index < data.length; index++) {
            var inc = {};
            inc['data.' + i] = 1;
            bulk.find( { '_id': doc._id } ).updateOne( { '$inc': inc } );
        }
        if (count % 200 === 0) {
             bulk.execute();
             bulk = db.collection.initializeOrderedBulkOp();
        }
    
    });
    
    if (count > 0)  bulk.execute();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2021-09-15
      • 2019-07-07
      • 2017-04-18
      • 2017-09-27
      • 2019-12-18
      • 2021-09-10
      相关资源
      最近更新 更多