惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 司徒正美
Google Online Security Blog
Google Online Security Blog
博客园_首页
量子位
大猫的无限游戏
大猫的无限游戏
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
Vercel News
Vercel News
GbyAI
GbyAI
Y
Y Combinator Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Cisco Blogs
IT之家
IT之家
A
Arctic Wolf
P
Privacy International News Feed
G
GRAHAM CLULEY
腾讯CDC
Microsoft Security Blog
Microsoft Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
美团技术团队
T
The Blog of Author Tim Ferriss
AWS News Blog
AWS News Blog
A
About on SuperTechFans
P
Proofpoint News Feed
I
Intezer
月光博客
月光博客
Cloudbric
Cloudbric
Google DeepMind News
Google DeepMind News
T
Tor Project blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
www.infosecurity-magazine.com
www.infosecurity-magazine.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Securelist
Engineering at Meta
Engineering at Meta
爱范儿
爱范儿
F
Full Disclosure
V2EX - 技术
V2EX - 技术
Last Week in AI
Last Week in AI
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
人人都是产品经理
人人都是产品经理
C
Check Point Blog
I
InfoQ
S
Security Affairs
Simon Willison's Weblog
Simon Willison's Weblog
P
Palo Alto Networks Blog
F
Fortinet All Blogs
S
Security @ Cisco Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
K
Kaspersky official blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security

Mereith's Blog

记一次代理转发问题的排查与解决 PVE DataCenter Manager 端口号跳转错误修复 k8s + jenkins + gitlab 触发器 【转载】没有编程生产力这样的东西 【后续】居然被 ddos 了 居然被 ddos 了 Tagger - 让版本标签管理更简单 openclash 开启后端口转发失效 nextjs 启动时执行代码 买了太多VPS不知道干什么,干脆做个网站 juhost Level-1 测评 VMISS CN - Hong Kong VMISS JP - Tokyo - BGP 测评 VMISS CN - Hong Kong - BGP HomeLab 的终点是 最近在做的事情 因为选择艰难症,自己写了一套开源博客系统 手撸一个nodejs分布式爬虫,还要可视化 HomeLab 分享 我的个人工作流——开源项目推荐 动手写一个超简单的编译器 safari 插件开发 Safari Extensions Preferences 按钮无响应 设置移动端软键盘回车按钮文案 nginx proxy manager 非标准端口反代 Host 不对 监控 k8s ingress 自动添加域名 DNS 解析 使用 ingress 注解给 traefik ingress 添加中间件 使用流水线功能为文章添加固定结尾 为 VanBlog 添加一个小挂件 基于React/umi/egg自建博客系统 如何正确停止 NodeJS 子进程 k8s pod 替换策略 让威联通、pve 共享 ups 实现断电关机 Ubuntu 配置 samba 混合云部署k3s集群(基于wireguard) pve 无法启动 grub lvmid not found error antd Password 关闭自动补全 code-server node not found pve no quorum 错误 || 无法登录 pve Cannot Initiate CMAP Service pve 节点删不干净 PVE 指针(鼠标)漂移 pve 重启网络 Proxmox VE 直通显卡 ProxmoxVE (PVE) 7.0 换源升级 用 SOCAT 端口转发 git 无法 pull 仓库refusing to merge unrelated histories 用 vuepress 搭建私人知识库 js 防抖节流中的 this 与箭头函数 Dockerfile 给 Ubuntu 换源 docker 内访问宿主机 docker 删除无用镜像 css 实现展开收起动画 nginx 301 问题 Node.js 流式编程 关于我重写了三次博客项目这件事 css flex 布局超出隐藏 css 隐藏滚动条 css 文字超出隐藏并显示省略号 css 填充 svg 颜色 css 黑白滤镜 nginx 反代丢端口 docker-compose 部署 matomo 分析系统 基于 strapi 开发应用 strapi 关闭 Content Security Policy nginx 反代 rewite url ssh 通过跳板机访问目标机器 Cent os 7 安装 zsh 5.6 以上版本 win11 任务栏不合并 bash 数组操作 vim 修改文件格式为 unix k8s 集群 control-plane-endpoint 主机名 git https 保存密码 Bash 判断命令存在 & 重定向 python 导出项目依赖 cent os 7 安装 gcc 版本 9 System limit for number of file watchers reached cent os 7 安装 git 2.x css 下划线中间向两边滑动效果 linux 挂载 SMB/CIFS linux 清除 ACL windows 命令行安装 inf 驱动 css 文字不可选择 iperf3 网络测速工具 cent os 换源 k8s 1.21.3 从 docker 迁移到 containerd 解决Nginx安装错误:No package nginx available 问题 从pve的硬盘里导出数据 Errors were encountered while processing adguardhome配合clash pve中使用LXC容器安装OMV LXC直通硬盘 nginx反代模版 docker常用开启容器的命令 PVE的LXC容器中安装Docker ProxmoxVE系统分区相关 基于clash搭建旁路网关 Portainer添加节点 linux声卡设置及录音音 OpenWrt用VLAN PVE换源及去掉订阅提示和改端口
Python操作MongoDB
wanglu@mereith.com (mereith) · 2022-07-21 · via Mereith's Blog

请注意,本文编写于 2221 天前,最后修改于 1416 天前,其中某些信息可能已经过时。

主要参考(抄袭)自:Python操作MongoDB看这一篇就够了

准备工作

你需要有个安装了MongoDB的服务器或者本地主机,另外请pip install pymongo一下。如果你不会装,请看我写的MongoDB的基本概念、安装及用户权限配置

连接MongoDB时,我们需要使用PyMongo库里面的MongoClient。一般来说,传入MongoDB的IP及端口即可,其中第一个参数为地址host,第二个参数为端口port(如果不给它传递参数,默认是27017):

import pymongo client = pymongo.MongoClient(host='localhost', port=27017)

这样就可以创建MongoDB的连接对象了。

另外,MongoClient的第一个参数host还可以直接传入MongoDB的连接字符串,它以mongodb开头,可以用它来指定密码账户等方式,例如:

client = MongoClient('mongodb://user:pwd@localhost:27017/')

关于连接的更多姿势,请看官方的连接字符串

指定数据库

MongoDB中可以建立多个数据库,接下来我们需要指定操作哪个数据库。这里我们以test数据库为例来说明,下一步需要在程序中指定要使用的数据库:


这里调用clienttest属性即可返回test数据库。当然,我们也可以这样指定:


这两种方式是等价的。

指定集合

MongoDB的每个数据库又包含许多集合(collection),它们类似于关系型数据库中的表。

下一步需要指定要操作的集合,这里指定一个集合名称为students。与指定数据库类似,指定集合也有两种方式:

collection = db.students #或者 collection = db['students']

这样我们便声明了一个Collection对象。

插入数据

接下来,便可以插入数据了。对于students这个集合,新建一条学生数据,这条数据以字典形式表示:

student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' }

这里指定了学生的学号、姓名、年龄和性别。接下来,直接调用collection的insert()方法即可插入数据,代码如下:

result = collection.insert(student) print(result)

MongoDB中,每条数据其实都有一个_id属性唯一标识。如果没有显式指明该属性,MongoDB会自动产生一个ObjectId类型的_id属性。insert()方法会在执行后返回_id值

运行结果如下:


当然,我们也可以同时插入多条数据,只需要以列表形式传递即可,示例如下:

student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male' } result = collection.insert([student1, student2]) print(result)

返回结果是对应的_id的集合

[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]

实际上,在PyMongo 3.x版本中,官方已经不推荐使用insert()方法了。当然,继续使用也没有什么问题。官方推荐使用insert_one()insert_many()方法来分别插入单条记录和多条记录,示例如下:

student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } result = collection.insert_one(student) print(result) print(result.inserted_id)

运行结果如下:

<pymongo.results.InsertOneResult object at 0x10d68b558> 5932ab0f15c2606f0c1cf6c5

insert()方法不同,这次返回的是InsertOneResult对象,我们可以调用其inserted_id属性获取_id

对于insert_many()方法,我们可以将数据以列表形式传递,示例如下:

student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male' } result = collection.insert_many([student1, student2]) print(result) print(result.inserted_ids)

运行结果如下:

<pymongo.results.InsertManyResult object at 0x101dea558> [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]

该方法返回的类型是InsertManyResult,调用inserted_ids属性可以获取插入数据的_id列表

查询

。。。写不动了 慢慢来