python – 在mongo中更新字段类型
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 在mongo中更新字段类型,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2192字,纯文字阅读大概需要4分钟。
内容图文
我在一个集合中有大量的记录:
{field: [value]}
我怎样才能有效地更新到:
{field:value}
我尝试过这样的事情:( pymongo语法)
collection.update({"field.1": {"$exists": True}},
{"$set": {'field': "field.1"}},
multi=True)
这显然不起作用.
由于记录数量很大,因此无法在循环中运行每个记录并删除插入.
解决方法:
您需要循环游标并使用$set update运算符更新每个文档.当然,为了达到最大效率,您可以使用“批量”操作.据说这种方法会有所不同,具体取决于您的MongoDB服务器版本和PyMongo版本.
从MongoDB 3.2开始,您需要使用Bulk Write Operations和bulkWrite()方法.
var requests = [];
var cursor = db.collection.find( { "field.1": { "$exists": true } }, { "field": 1 } );
cursor.forEach( document => {
requests.push({
"updateOne": {
"filter" : { "_id": document._id },
"update" : { "field": { "$set": document.field[0] } }
}
});
if (requests.length === 1000) {
db.collection.bulkWrite(requests);
requests = [];
}
});
if (requests.length > 0) {
db.collection.bulkWrite(requests);
}
使用PyMongo 3.0驱动程序提供您需要使用bulk_write()方法的此查询提供以下内容:
from pymongo import UpdateOne
requests = [];
cursor = db.collection.find({"field.1": {"$exists": True}}, {"field": 1})
for document in cursor:
requests.append(UpdateOne({'_id': document['_id']}, {'$set': {'field': document['field'][0]}}))
if len(requests) == 1000:
# Execute per 1000 operations
db.collection.bulk_write(requests)
requests = []
if len(requests) > 0:
# clean up queues
db.collection.bulk_write(requests)
从MongoDB 2.6开始,您需要使用现已弃用的Bulk API.
var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;
// cursor is the same as in the previous version using MongoDB 3.2
cursor.forEach(function(document) {
bulk.find( { "_id": document._id } ).updateOne( { "$set": { "field": document.field[0] } } );
count++;
if (count % 1000 === 0) {
bulk.execute();
bulk = db.collection.initializedUnorderedBulkOp();
}
});
// Again clean up queues
if (count > 0 ) {
bulk.execute();
}
转换为Python提供以下内容.
bulk = db.collection.initialize_unordered_bulk_op()
count = 0
for doc in cursor:
bulk.find({'_id': doc['_id']}).update_one({'$set': {'field': doc['field'][0]}})
count = count + 1
if count == 1000:
bulk.execute()
bulk = db.collection.initialize_unordered_bulk_op()
if count > 0:
bulk.execute()
内容总结
以上是互联网集市为您收集整理的python – 在mongo中更新字段类型全部内容,希望文章能够帮你解决python – 在mongo中更新字段类型所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。