MongoDB - String转换为Int,并更新到数据库中

方法1 pymongo。使用$convert, MongoDB版本 >= 4,速度快。

# 假设{'age': '47'}, 转换后为{'age': 47}
import time
import pymongo

start_time = time.time()
handler = pymongo.MongoClient().db_name.collections_name
handler.update_many({}, [
    {'$set':
         {'age':
              {'$convert':
                   {'input': '$age', 'to': 'int'}
               }
          }
     }
])
end_time = time.time()
print('耗时:', end_time - start_time)

方法2 原生语句和pymongo。逐个转换,速度慢,兼容各版本MongoDB。

使用原生mongo语句示范(在robo3T或者在命令行上输入)

# 假设{'salary': '123'}, 转换后为{'salary': 123}
db.getCollection("collection_name").find({salary: {$exists: true}}).forEach(function(obj) { 
    obj.salary = new NumberInt(obj.salary);
    db.db_name.save(obj);
});

db.getCollection('example_data_1').find({}).forEach(function(document){
        document.age = parseInt(document.age);
        db.getCollection('example_data_1').save(document);
})

使用pymongo,在python层进行类型转换

import time
import pymongo


start_time = time.time()
handler = pymongo.MongoClient().db_name.collection_name
for row in handler.find({}, {'salary': 1}):
    salary = int(row['salary'])
    handler.update_one({'_id': row['_id']}, {'$set': {'salary': salary}})
end_time = time.time()
print('耗时:', end_time - start_time)

方法3 pymongo。使用插入代替更新,速度快

相当于新建一个新的collection,然后删除原本的collection。因为是insert_many,所以速度快。经过测试,db.find()和xxx_many(insert_many、update_many)速度都很快。所以有一个前提:MongoDB中批量操作比逐个操作快多了。
以下操作不但做转换操作,还做了每个salary都加上100
使用pymongo示范

import time
import pymongo


start_time = time.time()
db = pymongo.MongoClient().db_name
old_collection = db.old_collection
new_collection = db.new_collection
new_people_info_list = []
for row in old_collection.find():
    salary = int(row['salary'])
    new_salary = salary + 100
    new_people_info_list.append(row)
new_collection.insert_many(new_people_info_list)
end_time = time.time()
print('耗时:', end_time - start_time)


参考

  1. https://docs.mongodb.com/manual/reference/operator/aggregation/convert/#example
  2. https://stackoverflow.com/questions/4973095/how-to-change-the-type-of-a-field
posted @ 2019-08-31 22:54  Rocin  阅读(4113)  评论(0编辑  收藏  举报