如何使用pymongo增加数组/列表中每个元素的值?

时间:2015-12-01 15:33:52

标签: python mongodb mongodb-query pymongo

$ 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]
}

你能建议我,我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

您需要使用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();