MongoDB - String converted to Int, and updates to the database

Method 1 using $ convert, MongoDB version> = 4, speed.

Use pymongo demonstration

# 假设{'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)

Method 2 converted one by one, slowly, compatible with all versions of MongoDB.

Mongo exemplary statement using the native (or input on the command line 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);
});

In fact, there are several ways to convert, I only practiced methods 1 and 2

reference

  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

Guess you like

Origin www.cnblogs.com/allen2333/p/11440877.html