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

使用pymongo示范,原生mongo语句并没有尝试。

# 假设{'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 逐个转换,速度慢,兼容各版本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);
});

使用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 使用插入代替更新,速度快

相当于新建一个新的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

MongoDB - String转换为Int,并更新到数据库中的更多相关文章

  1. string[]转换为int[]

    今天碰到一个问题,要把string[]转换为int[],但是又不想使用循环转换,找了好久最后找到了这种方法,特此记录下. string[] input = { "1", " ...

  2. PowerDesigner如何将设计的表更新到数据库中

    前言: 软件开发的过程中,将设计的表更新到数据库中是一件繁琐的事情,使用好工具,能够事半功倍. 环境介绍:Oracle 11g x64 前期准备: 1.PowerDesigner工具(本人是32位的) ...

  3. string[] 转换为 int[]

    string[] ke=...... int[] output = Array.ConvertAll<string, int>(ke,delegate (string s) { retur ...

  4. oracle不小心更新了数据库中的所有内容后的恢复

    开发过程中,在更新数据库中的某一条数据时,由于疏忽忘记加where判断条件了,这时更新会提示是否要更新全部数据,但是由于自己没有仔细看提示导致直接点确定并commit了,导致数据库中所有数据的相关字段 ...

  5. 一个简单的批量更新oracle 数据库中 最近的服务商名称的数据

    有一个需求是这样的,我们需要更新数据库中的数据,数据时这样的 1.大约50万以上 2. 数据中有较多的重复数据 3. 需要将表中最近的代理商的名称赋值给行中的服务商名称 4. 代理商的名称可能有多个, ...

  6. php string转换为int

    本身 var_dump : string(3) "002" 本身 is_numeric : bool(true) 本身 转换为数字 : int(2) 本身 转换为数字变量 : in ...

  7. 如何将String转换为int

    1. int i = Integer.parseInt([String]); 或 i = Integer.parseInt([String],[int radix]); Integer.parseIn ...

  8. valueof这个万能方法,将string转换为int或者int转换为string都可以

    private static String testString = "111"; int stringInt = Integer.valueOf(testString); Str ...

  9. Python 实int型和list相互转换 现把float型列表转换为int型列表 把列表中的数字由float转换为int型

    第一种方法:使用map方法 >>> list = [, ] #带有float型的列表 >>> int_list = map(int,list) #使用map转换 & ...

随机推荐

  1. P4802 [CCO 2015]路短最

    Problem 这题的题意是 求一条 经过 起点和终点的 最长路径.且一个点只能经过一次. 我们设定 \(dis_{i,j}\) 为 i 到 j 的距离(应该没有重边) 要注意的是 不能用 \(Flo ...

  2. Nuxt服务端使用Axios调用接口时传递cookies

    个人博客 地址:http://www.wenhaofan.com/article/20190321183709 介绍 在做单点登录时,后端需要根据cookie获取登录用户,由于前端项目使用了Nuxt做 ...

  3. python django项目的搭建及初始配置

    1.创建项目并创建应用 django-admin startproject my_project # 创建项目python manage.py startapp my_app # 创建应用 1.1 项 ...

  4. Educational Codeforces Round 65 (Rated for Div. 2)B. Lost Numbers(交互)

    This is an interactive problem. Remember to flush your output while communicating with the testing p ...

  5. openWRT和LuCI

    openwrt是一套集成在板子上的系统,通过ip进入到其页面上 Luci是lua和UCI统一配置接口的合体,实现路由的网页配置界面(相当于一个前端框架)

  6. Longest Ordered Subsequence POJ - 2533 dp 最长上升/不下降 子序列

    #include<iostream> using namespace std ; ; int f[N]; int a[N]; int n; int main() { cin>> ...

  7. Subway POJ - 2502 spfa

    #include<cstdio> #include<cmath> #include<cstring> #include<cstring> #includ ...

  8. 401 WebEx会议教程一 —— 参加会议

    · WebEx会议教程一 —— 参加会议 参加他人发起的会议 1.  在邀请邮件中,接受对方的会议邀请: 2.  一般在WebEx会议开始前15分钟时,邮箱客户端会提醒您 (如下图类似提示) 3.   ...

  9. 关于Oracle的使用

    1.查看数据库 在sqlplus / as sysdba执行后,再执行select name from v$database; 2.执行1后继续查看该数据库下的表 select table_name ...

  10. dubbo整合SSM登录案例

    基于dubbo/zookeeper/SSM的分布式工程   一.项目结构