方法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)