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

2024-10-02 16:26:14 发布

您现在位置:Python中文网/ 问答频道 /正文

$inc在更新中对一个数字有效-

{
     _id:1,
    data:5
}

可以更新数据-

^{pr2}$

数据是更新后的总和-

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

你能建议我,我怎样才能做到这一点?在


Tags: 数据iddbdata错误codeupdate数字
1条回答
网友
1楼 · 发布于 2024-10-02 16:26:14

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

>>> 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中这样做:

^{pr2}$

相关问题 更多 >