2015-12-01 25 views
-1

$ INC在更新工作正常,一個數字 -如何使用pymongo增加數組/列表中每個元素的值?

可以更新數據 -

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

能否請你給我建議,我怎麼能做到這一點?

回答

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')}] 
>>> 

你也可以做到這一點在這樣的外殼:

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(); 
相關問題