python 操作 mongoDB

模块

pymongo

安装方法

sudo pip3 install pymongo

操作步骤

1. 创建数据库连接对象

conn = pymonge.MomgoClient("localhost",27017)

2. 生成操作的数据库对象

db = conn.stu

3. 生成集合对象

myset = db.class0

4. 通过 集合对象 调用结构完成数据操作

['_BaseObject__codec_options',
'_BaseObject__read_concern',
'_BaseObject__read_preference',
'_BaseObject__write_concern',
'_Collection__create',
'_Collection__create_index',
'_Collection__database',
'_Collection__find_and_modify',
'_Collection__full_name',
'_Collection__name',
'_Collection__write_response_codec_options',
'__call__',
'__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattr__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__init__',
'__iter__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__next__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'_command',
'_count',
'_delete',
'_insert',
'_insert_one',
'_legacy_write',
'_socket_for_primary_reads',
'_socket_for_reads',
'_socket_for_writes',
'_update',
'aggregate',
'bulk_write',
'codec_options',
'count',
'create_index',
'create_indexes',
'database',
'delete_many',
'delete_one',
'distinct',
'drop',
'drop_index',
'drop_indexes',
'ensure_index',
'find',
'find_and_modify',
'find_one',
'find_one_and_delete',
'find_one_and_replace',
'find_one_and_update',
'full_name',
'group',
'index_information',
'initialize_ordered_bulk_op',
'initialize_unordered_bulk_op',
'inline_map_reduce',
'insert',
'insert_many',
'insert_one',
'list_indexes',
'map_reduce',
'name',
'next',
'options',
'parallel_scan',
'read_concern',
'read_preference',
'reindex',
'remove',
'rename',
'replace_one',
'save',
'update',
'update_many',
'update_one',
'with_options',
'write_concern']

集合对象内的所有方法

5. 关闭数据库连接

db.close()

数据操作

插入文档

insert_many     插入多条
insert_one 插入一条
insert 插入一条或多条
save 保存文档

实例

myset.insert_one({"name":"张铁林","King":"乾隆"})
myset.insert_many([{"name":"张国立","King":"康熙"}, {"name":"陈道明","King":"康熙"}])
myset.insert({"name":"唐国强","King":"雍正"})
myset.insert([{"name":"陈建斌","King":"雍正"}, {"_id":1, "name":"吴奇隆","King":"四爷"}])
myset.save({"_id":1,"name":"聂远","King":"乾隆"})

查找文档

find        查找所有
find_one 查找首个

find

find(query,field)

参数形式  同 mongoshell 中的 find

返回值   游标对象

对比 mongoDB 的语句

  所有的操作符加上引号,作为字符串形式

  true/false/null 改成 True/False/None

实例

cursor = myset.find({"name":{"$exists":True}},{"_id":0})

for i in cursor:
# print(i)
print(i["name"],"--",i["King"])

cursor 对象属性函数

cursor 本质为返回的文档集合的序列, 同 mongoDB 一样可以继续调用其他的精确筛选方法

next()      获取下一个文档
limit() 获取前几条文档
skip() 跳过几条
count() 计数
sort() 排序
* sort 的参数发生了变化 sort([(域名,1/-1),(),()...])
* limit,sort,skip 使用时, 必须保证游标在最开始的位置

实例

 # for i in cursor.limit(3):
# for i in cursor.skip(3):
# for i in cursor.sort([("name",1),("age",-1)]):
for i in cursor.sort([("name",1)]):
print(i)

find_one

find_one(query,field)

功能  查找首个符合条件的文档

参数  同 find

返回值  返回字典(只查到首条, 因此返回数据也是单数据, 即 字典)

实例

dic = {"$or":[{"King":"乾隆"},{"name":"陈道明"}]}
d = myset.find_one(dic,{"_id":0})
print(d)

修改操作

update_one      修改一个
update_many 修改多个
update 修改一个或多个

实例

myset.update_many({"King":"康熙"},{"$set":{"king_name":"玄烨"}})
myset.update_one({"King":"雍正"},{"$set":{"king_name":"忘了名字"}})
myset.update_one({"name":"郑少秋"},{"$set":{"King":"乾隆"}},upsert=True)
myset.update({"King":"乾隆"},{"$set":{"king_name":"弘历"}})
myset.update({"King":"乾隆"},{"$set":{"king_name":"弘历"}},multi=True)

删除操作

delete_one      删除一个
delete_many 删除多个
remove 删除一个或多个

实例

myset.delete_one({"King":"康熙"})
myset.delete_many({"King":"雍正"})
myset.remove({"king_name":{"$exists":False}})
myset.remove({"king_name":None},multi=True)

复合操作

find_one_and_update
find_one_and_delete

实例

data = myset.find_one_and_delete({"name":"张铁林"})
print(data)

文档操作整体实例

from pymongo import MongoClient

# 创建数据库链接
conn = MongoClient("localhost",27017) # 创建数据库对象
db = conn.stu
# db = conn["stu"] # 生成集合对象
myset = db.class0
# myset = db["class0"] # 创建集合对象
myset = db.class4 # 数据操作 # -----------------------insert----------------------
# myset.insert_one({"name":"张铁林","King":"乾隆"}) # myset.insert_many([{"name":"张国立","King":"康熙"},\
# {"name":"陈道明","King":"康熙"}]) # myset.insert({"name":"唐国强","King":"雍正"})
# myset.insert([{"name":"陈建斌","King":"雍正"},\
# {"_id":1, "name":"吴奇隆","King":"四爷"}]) # myset.save({"_id":1,"name":"聂远","King":"乾隆"}) # ----------------------find-----------------------
# cursor = myset.find({"name":{"$exists":True}},{"_id":0})
# print(cursor.next()) # 打印下一个文档
# for i in cursor:
# print(i)
# print(i["name"],"--",i["King"])
# 所有的操作符加上引号,作为字符串形式
# true/false/null 改成 True/False/None # for i in cursor.limit(3):
# for i in cursor.skip(3):
# for i in cursor.sort([("name",1),("age",-1)]):
# for i in cursor.sort([("name",1)]):
# print(i)
# limit,sort,skip 使用时, 必须保证游标在最开始的位置 # dic = {"$or":[{"King":"乾隆"},{"name":"陈道明"}]}
# d = myset.find_one(dic,{"_id":0})
# print(d) # ----------------------update-----------------------
# myset.update_many({"King":"康熙"},{"$set":{"king_name":"玄烨"}})
# myset.update_one({"King":"雍正"},{"$set":{"king_name":"忘了名字"}})
# myset.update_one({"name":"郑少秋"},{"$set":{"King":"乾隆"}},upsert=True)
# myset.update({"King":"乾隆"},{"$set":{"king_name":"弘历"}})
# myset.update({"King":"乾隆"},{"$set":{"king_name":"弘历"}},multi=True) # ------------------------delete----------------------
# myset.delete_one({"King":"康熙"})
# myset.delete_many({"King":"雍正"})
# myset.remove({"king_name":{"$exists":False}})
# myset.remove({"king_name":None},multi=True) # ------------------------复合操作----------------------
# data = myset.find_one_and_delete({"name":"张铁林"})
# print(data) # 关闭链接
conn.close()

索引操作

create_index    创建索引
参数: 二元元组构成列表
create_index([("age",1)])
create_index([("age",1),("name":-1)])
也可以直接写 域名 ("age") 表示对该域创建正向索引
返回值: 索引名称
list_indexes 查看索引
drop_index 删除索引
drop_indexes 删除所有索引

聚合操作

aggregate()

功能  完成聚合操作

参数  聚合管道, 同mongoshell 中的聚合

返回值  数据操作结果游标对象

实例

lis = [
{"$group": {"_id": "$sex", "num": {"$sum": 1}}},
]
cursor = myset.aggregate(lis)

索引聚合实例

from pymongo import MongoClient

conn = MongoClient("localhost", 27017)
db = conn.stu
myset = db.class0 # -------------------------------索引--------------------------------
# 创建
# index_name = myset.create_index("name")
# index_age = myset.create_index("age",name="Age",sparse=True)
# index_age = myset.create_index("age",name="Age",sparse=True,unique=True) #  删除索引
# myset.drop_index("Age")
# myset.drop_indexes() # 查看
# for i in myset.list_indexes():
# print(i) # ------------------------------聚合----------------------------------
lis = [
{"$group": {"_id": "$sex", "num": {"$sum": 1}}},
] cursor = myset.aggregate(lis)
for i in cursor:
print(i) conn.close()

文件操作

1. 导入bson 二进制模块,连接数据库

import bson.binary

2. 选择要存储的文件, 使用 rb 方式读取内容

3. 将读取的内容转换为 bson 格式

content = bson.binary.Binary(data)

  功能  将 bytes 字串 转换为 bson 格式

  参数  bytes 字串

  返回值  转换后的数据

4. 将内容插入到数据库

实例

from pymongo import MongoClient
import bson.binary conn = MongoClient("localhost",27017)
db = conn.image
myset = db.mm # --------------------存储----------------------------------
# 读取图片内容
# with open("123.PNG","rb") as f:
# data = f.read() # 格式转化
# conntent = bson.binary.Binary(data) # 插入数据库
# myset.insert_one({"filename":"123.jpg","data":conntent}) #--------------------取出文件-------------------------------
# img = myset.find_one({"filename":"123.jpg"}) # 写入本地
# with open("123.jpg","wb") as f: # find_one 会自动转换不需要自己再转换了
# f.write(img["data"]) conn.close()

pymongo 操作的更多相关文章

  1. python操作三大主流数据库(8)python操作mongodb数据库②python使用pymongo操作mongodb的增删改查

    python操作mongodb数据库②python使用pymongo操作mongodb的增删改查 文档http://api.mongodb.com/python/current/api/index.h ...

  2. Python 使用pymongo操作mongodb库

    Python 使用pymongo操作mongodb库 2016-12-31 21:55 1115人阅读 评论(0) 收藏 举报  分类: - - - Python(10)  版权声明:本文为博主原创文 ...

  3. pymongo操作mongodb

    此验证中只开启两个mongodb节点,可以连接任意节点,以下操作不涉及读写,不涉及连接那个节点 mongodb连接: from pymongo import MongoReplicaSetClient ...

  4. python中使用pymongo操作mongo

    MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档.数组及文档数组,非常灵活.在这一节中,我们就来看 ...

  5. pymongo操作mongo数据库的查操作

    一:  数据结构 { "_id" : ObjectId("5de8a5b748a75a8d48b72bdc"), ", ", ", ...

  6. MongoDB学习【四】—pymongo操作mongodb数据库

    一.pymongodb的安装 Python 要连接 MongoDB 需要 MongoDB 驱动,这里我们使用 PyMongo 驱动来连接. pip安装 pip 是一个通用的 Python 包管理工具, ...

  7. python 通过pymongo操作mongoDB执行sort

    在mongo shell 中对数据进行排序操作的时候 db.getCollection('ANJUKE_PRICE').find({},{'id':1,'_id':0}).sort({'id':1}) ...

  8. MongoDB、PyMongo数据操作

    MongoDB 命令 C:\Program Files\MongoDB\Server\4.0\bin mongo 客户端 mongod 服务端 mongoexport 导出 普通格式,每条记录一行,整 ...

  9. python操作mongoDB(pymongo的使用)

    pymongo操作手册 连接数据库 方法一(推荐) import pymongo client = pymongo.MongoClient(host="localhost",por ...

随机推荐

  1. C# Html格式内容转Csv内容包括table(重点在rowspan和colspan合并),p,div元素

    Html格式内容转Csv内容,包括table(重点在rowspan和colspan合并),p,div元素,table不能包含嵌套功能. /// <summary> /// Html格式内容 ...

  2. Review: Basic Knowledge about SQL

    非原创,转自Github:enochtangg/quick-SQL-cheatsheet SQL 语句用法的速查表. 内容 查找数据的查询 修改数据的查询 聚合查询 连接查询 视图查询 修改表的查询 ...

  3. nginx实现新老网站跳转(原URL不变)

    新老网站实现跳转 原URL保持不变 通过手动添加cookie 匹配cookie的方法进行跳转第一步 进行添加if判断条件 if ( $query_string ~* "sr=pro" ...

  4. es crul查询(一)

    C:\Users\Administrator>elasticdump --input=D:\test --output=http://localhost:9200/logs_apipki_201 ...

  5. linux 系统信息展示 htop glances conky psensor

    htop glances conky psensor htop glances 只能在终端内展示. htop 使用系统自带程序包管理程序就可以安装 glances github地址:https://g ...

  6. Linux-基础学习(一)-基本命令

    开始今日份整理 1.Linux的文件目录操作 1.1 ls 简述:ls是list的缩写,用于列出指定目录或文件 常用的选项 1 -a:显示所有档案及目录(ls内定将档案名或目录名称为“.”的视为隐藏, ...

  7. identity server4 证书

    我们需要对token进行签名, 这意味着identity server需要一对public和private key. 幸运的是, 我们可以告诉identity server在程序的运行时候对这项工作进 ...

  8. (十三)Batch Processing

    In addition to being able to index, update, and delete individual documents, Elasticsearch also prov ...

  9. debug和release版本的区别

    Debug:调试版本,包含调试信息,所以容量比Release大很多,并且不进行任何优化(优化会使调试复杂化,因为源代码和生成的指令间关系会更复杂),便于程序员调试. Debug模式下生成两个文件,除了 ...

  10. Scrapy中选择器的用法

    官方文档:https://doc.scrapy.org/en/latest/topics/selectors.html Using selectors Constructing selectors R ...