Python操作MongoDB文档数据库
1.Pymongo 安装
安装pymongo:
pip install pymongo
- PyMongo是驱动程序,使python程序能够使用Mongodb数据库,使用python编写而成;
2.Pymongo 方法
insert_one()
:插入一条记录;insert()
:插入多条记录;find_one()
:查询一条记录,不带任何参数返回第一条记录,带参数则按条件查找返回;find()
:查询多条记录,不带参数返回所有记录,带参数按条件查找返回;count()
:查看记录总数;create_index()
:创建索引;update_one()
:更新匹配到的第一条数据;update()
:更新匹配到的所有数据;remove()
:删除记录,不带参表示删除全部记录,带参则表示按条件删除;delete_one()
:删除单条记录;delete_many()
:删除多条记录;
3.Pymongo 中的操作
- 查看数据库
from pymongo import MongoClient
connect = MongoClient(host='localhost', port=27017, username="root", password="123456")
connect = MongoClient('mongodb://localhost:27017/', username="root", password="123456")
print(connect.list_database_names())
- 获取数据库实例
test_db = connect['test']
- 获取collection实例
collection = test_db['students']
- 插入一行document, 查询一行document,取出一行document的值
from pymongo import MongoClient
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",)
# 获取db
test_db = connect['test']
# 获取collection
collection = test_db['students']
# 构建document
document = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.now()}
# 插入document
one_insert = collection.insert_one(document=document)
print(one_insert.inserted_id)
# 通过条件过滤出一条document
one_result = collection.find_one({"author": "Mike"})
# 解析document字段
print(one_result, type(one_result))
print(one_result['_id'])
print(one_result['author'])
注意:如果需要通过id查询一行document,需要将id包装为ObjectId类的实例对象
from bson.objectid import ObjectId
collection.find_one({'_id': ObjectId('5c2b18dedea5818bbd73b94c')})
- 插入多行documents, 查询多行document, 查看collections有多少行document
from pymongo import MongoClient
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",)
# 获取db
test_db = connect['test']
# 获取collection
collection = test_db['students']
documents = [{"author": "Mike","text": "Another post!","tags": ["bulk", "insert"], "date": datetime(2009, 11, 12, 11, 14)},
{"author": "Eliot", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime(2009, 11, 10, 10, 45)}]
collection.insert_many(documents=documents)
# 通过条件过滤出多条document
documents = collection.find({"author": "Mike"})
# 解析document字段
print(documents, type(documents))
print('*'*300)
for document in documents:
print(document)
print('*'*300)
result = collection.count_documents({'author': 'Mike'})
print(result)
- 范围比较查询
from pymongo import MongoClient
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",)
# 获取db
test_db = connect['test']
# 获取collection
collection = test_db['students']
# 通过条件过滤时间小于datetime(2019, 1,1,15,40,3) 的document
documents = collection.find({"date": {"$lt": datetime(2019, 1,1,15,40,3)}}).sort('date')
# 解析document字段
print(documents, type(documents))
print('*'*300)
for document in documents:
print(document)
- 创建索引
from pymongo import MongoClient
import pymongo
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",)
# 获取db
test_db = connect['test']
# 获取collection
collection = test_db['students']
# 创建字段索引
collection.create_index(keys=[("name", pymongo.DESCENDING)], unique=True)
# 查询索引
result = sorted(list(collection.index_information()))
print(result)
- document修改
from pymongo import MongoClient
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",)
# 获取db
test_db = connect['test']
# 获取collection
collection = test_db['students']
result = collection.update({'name': 'robby'}, {'$set': {"name": "Petter"}})
print(result)
注意:还有update_many()方法
- document删除
from pymongo import MongoClient
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",)
# 获取db
test_db = connect['test']
# 获取collection
collection = test_db['students']
result = collection.delete_one({'name': 'Petter'})
print(result.deleted_count)
注意:还有delete_many()方法
4.MongoDB ODM 详解
- MongoDB ODM 与 Django ORM使用方法类似;
- MongoEngine是一个对象文档映射器,用Python编写,用于处理MongoDB;
- MongoEngine提供的抽象是基于类的,创建的所有模型都是类;
# 安装mongoengine
pip install mongoengine
- mongoengine使用的字段类型
BinaryField
BooleanField
ComplexDateTimeField
DateTimeField
DecimalField
DictField
DynamicField
EmailField
EmbeddedDocumentField
EmbeddedDocumentListField
FileField
FloatField
GenericEmbeddedDocumentField
GenericReferenceField
GenericLazyReferenceField
GeoPointField
ImageField
IntField
ListField:可以将自定义的文档类型嵌套
MapField
ObjectIdField
ReferenceField
LazyReferenceField
SequenceField
SortedListField
StringField
URLField
UUIDField
PointField
LineStringField
PolygonField
MultiPointField
MultiLineStringField
MultiPolygonField
5.使用mongoengine创建数据库连接
from mongoengine import connect
conn = connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin')
print(conn)
connect(db = None,alias ='default',** kwargs );
db
:要使用的数据库的名称,以便与connect兼容;host
:要连接的mongod实例的主机名;port
:运行mongod实例的端口;username
:用于进行身份验证的用户名;password
:用于进行身份验证的密码;authentication_source
:要进行身份验证的数据库;
构建文档模型,插入数据
from mongoengine import connect, \
Document, \
StringField,\
IntField, \
FloatField,\
ListField, \
EmbeddedDocumentField,\
DateTimeField, \
EmbeddedDocument
from datetime import datetime
# 嵌套文档
class Score(EmbeddedDocument):
name = StringField(max_length=50, required=True)
value = FloatField(required=True)
class Students(Document):
choice = (('F', 'female'),
('M', 'male'),)
name = StringField(max_length=100, required=True, unique=True)
age = IntField(required=True)
hobby = StringField(max_length=100, required=True, )
gender = StringField(choices=choice, required=True)
# 这里使用到了嵌套文档,这个列表中的每一个元素都是一个字典,因此使用嵌套类型的字段
score = ListField(EmbeddedDocumentField(Score))
time = DateTimeField(default=datetime.now())
if __name__ == '__main__':
connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin')
math_score = Score(name='math', value=94)
chinese_score = Score(name='chinese', value=100)
python_score = Score(name='python', value=99)
for i in range(10):
students = Students(name='robby{}'.format(i), age=int('{}'.format(i)), hobby='read', gender='M', score=[math_score, chinese_score, python_score])
students.save()
查询数据
from mongoengine import connect, \
Document, \
StringField,\
IntField, \
FloatField,\
ListField, \
EmbeddedDocumentField,\
DateTimeField, \
EmbeddedDocument
from datetime import datetime
# 嵌套文档
class Score(EmbeddedDocument):
name = StringField(max_length=50, required=True)
value = FloatField(required=True)
class Students(Document):
choice = (('F', 'female'),
('M', 'male'),)
name = StringField(max_length=100, required=True, unique=True)
age = IntField(required=True)
hobby = StringField(max_length=100, required=True, )
gender = StringField(choices=choice, required=True)
# 这里使用到了嵌套文档,这个列表中的每一个元素都是一个字典,因此使用嵌套类型的字段
score = ListField(EmbeddedDocumentField(Score))
time = DateTimeField(default=datetime.now())
if __name__ == '__main__':
connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin')
first_document = Students.objects.first()
all_document = Students.objects.all()
# 如果只有一条,也可以使用get
specific_document = Students.objects.filter(name='robby3')
print(first_document.name, first_document.age, first_document.time)
for document in all_document:
print(document.name)
for document in specific_document:
print(document.name, document.age)
修改、更新、删除数据
from mongoengine import connect, \
Document, \
StringField,\
IntField, \
FloatField,\
ListField, \
EmbeddedDocumentField,\
DateTimeField, \
EmbeddedDocument
from datetime import datetime
# 嵌套文档
class Score(EmbeddedDocument):
name = StringField(max_length=50, required=True)
value = FloatField(required=True)
class Students(Document):
choice = (('F', 'female'),
('M', 'male'),)
name = StringField(max_length=100, required=True, unique=True)
age = IntField(required=True)
hobby = StringField(max_length=100, required=True, )
gender = StringField(choices=choice, required=True)
# 这里使用到了嵌套文档,这个列表中的每一个元素都是一个字典,因此使用嵌套类型的字段
score = ListField(EmbeddedDocumentField(Score))
time = DateTimeField(default=datetime.now())
if __name__ == '__main__':
connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin')
specific_document = Students.objects.filter(name='robby3')
specific_document.update(set__age=100)
specific_document.update_one(set__age=100)
for document in specific_document:
document.name = 'ROBBY100'
document.save()
for document in specific_document:
document.delete()
all()
:返回所有文档;all_fields()
:包括所有字段;as_pymongo()
:返回的不是Document实例 而是pymongo值;average()
:平均值超过指定字段的值;batch_size()
:限制单个批次中返回的文档数量;clone()
:创建当前查询集的副本;comment()
:在查询中添加注释;count()
:计算查询中的选定元素;create()
:创建新对象,返回保存的对象实例;delete()
:删除查询匹配的文档;distinct()
:返回给定字段的不同值列表;
嵌入式文档查询的方法
count()
:列表中嵌入文档的数量,列表的长度;create()
:创建新的嵌入式文档并将其保存到数据库中;delete()
:从数据库中删除嵌入的文档;exclude(** kwargs )
:通过使用给定的关键字参数排除嵌入的文档来过滤列表;first()
:返回列表中的第一个嵌入文档;get()
:检索由给定关键字参数确定的嵌入文档;save()
:保存祖先文档;update()
:使用给定的替换值更新嵌入的文档;
Python操作MongoDB文档数据库的更多相关文章
- Python 操作 mongodb 数据库
原文地址:https://serholiu.com/python-mongodb 这几天在学习Python Web开发,于 是做准备做一个博客来练练手,当然,只是练手的,博客界有WordPress这样 ...
- python操作mongodb
# python操作mongodb # 首先,引入第三方模块pymongo,该模块是python用来操作mongodb的 import pymongo # 第二步,设置ip地址,以及表格名称,表格名字 ...
- 使用Python操作MongoDB
MongoDB简介(摘自:http://www.runoob.com/mongodb/mongodb-intro.html) MongoDB 由C++语言编写,是一个基于分布式文件存储的开源数据库系统 ...
- python操作三大主流数据库(10)python操作mongodb数据库④mongodb新闻项目实战
python操作mongodb数据库④mongodb新闻项目实战 参考文档:http://flask-mongoengine.readthedocs.io/en/latest/ 目录: [root@n ...
- python操作三大主流数据库(9)python操作mongodb数据库③mongodb odm模型mongoengine的使用
python操作mongodb数据库③mongodb odm模型mongoengine的使用 文档:http://mongoengine-odm.readthedocs.io/guide/ 安装pip ...
- python操作三大主流数据库(8)python操作mongodb数据库②python使用pymongo操作mongodb的增删改查
python操作mongodb数据库②python使用pymongo操作mongodb的增删改查 文档http://api.mongodb.com/python/current/api/index.h ...
- python操作三大主流数据库(7)python操作mongodb数据库①mongodb的安装和简单使用
python操作mongodb数据库①mongodb的安装和简单使用 参考文档:中文版:http://www.mongoing.com/docs/crud.html英文版:https://docs.m ...
- MongoDB的安装与python操作MongoDB
一.安装MongoDB 因为我个人使用的是windows,就只记录下windows下的安装 1.下载安装 就是官网,下载msi,选个路径安装 2.配置 看见别的地方说需要手动在bin同级目录创建dat ...
- python 操作mongoDB数据库
网上关于python 操作mongoDB的相关文章相对不是很多,并且质量也不是很高!下面给出一个完整的 增删改查示例程序! #!/usr/bin/python # -*- coding: utf-8 ...
随机推荐
- awk文本处理
一.前言 (一).awk简介 awk是一种编程语言,用于在linux/unix下对文本和数据进行处理,数据可以来自标准输入.一个或多个文件,或其它命令的输出,它支持用户自定义函数和动态正则表达式等先进 ...
- Robotframework获取移动端toast问题
背景: 在做移动端自动化测试的时候,经常会遇到一个问题就是获取toast提示问题,如果需要解决这个问题需要重新处理,不能按照正常的逻辑,使用robotframework自带的关键字进行获取,需要重新考 ...
- java高并发系列 - 第23天:JUC中原子类,一篇就够了
这是java高并发系列第23篇文章,环境:jdk1.8. 本文主要内容 JUC中的原子类介绍 介绍基本类型原子类 介绍数组类型原子类 介绍引用类型原子类 介绍对象属性修改相关原子类 预备知识 JUC中 ...
- 第四章 文件的基本管理和XFS文件系统备份恢复 随堂笔记
第四章 文件的基本管理和XFS文件系统备份恢复 本节所讲内容: 4.1 Linux系统目录结构和相对/绝对路径. 4.2 创建/复制/删除文件,rm -rf / 意外事故 4.3 查看文件内容的命令 ...
- Two types of people with high scores of English exams
I believe that there are two types of people who get high scores in English exams: 1) have high inte ...
- 转载 | CSS实现单行、多行文本溢出显示省略号(…)
本文引自:https://www.cnblogs.com/wyaocn/p/5830364.html 首先,要知道css的三条属性. overflow:hidden; //超出的文本隐藏 text-o ...
- PHP版本的区别与用法详解
在我们安装PHP模块时,有时需要注意PHP编译的版本,下面讲解下PHP中VC6.VC9.TS.NTS版本的区别与用法详解,介绍php的两种执行方式. 1. VC6与VC9的区别:VC6版本是使用Vis ...
- Python 学习笔记(6)— 字符串格式化
字符串格式化处理 远古写法 以前通常使用运算符号 % ,%s 插入的值 String 类型,%.3f 指插入的值为包含 3 位小数的浮点数: format1 = "%s, %s!" ...
- React Native 混合开发与实现
关于 微信公众号:前端呼啦圈(Love-FED) 我的博客:劳卜的博客 知乎专栏:前端呼啦圈 前言 随着 React 的盛行,其移动开发框架 React Native 也收到了广大开发者的青睐,以下简 ...
- Nginx 502 Bad Gateway 错误的解决方法
502 bad gateway 的解决方法 通用配置 proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小 proxy_buffers 4 32k; # ...