数据库的操作无非是要掌握数据库的增,改,删,此篇文章为查阅官方文档的翻译和解释。
官方文档:Tutorial — PyMongo 3.7.1 documentation http://api.mongodb.com/python/current/tutorial.html
Prerequisites先决条件
已经安装了pymongo,并且import pymongo
没有报错
(pymongo安装:在cmd中输入pip3 install pymongo
)
Making a Connection with MongoClient
连接MongoDB实例的客户端
1.from pymongo import MongoClient
没有添加参数时,会连接默认的用户和端口
client = MongoClient()
2.但是可以指定用户和端口client = MongoClient('localhost', 27017)
3.或者用MongoDB URI 形式
client = MongoClient('mongodb://localhost:27017/')
Getting a Database得到数据库
db = client.test_database
如果数据库名称不能直接用客户端.数据名的方式引用,如test-database
那就使用字典的方式引用:db = client['test-database']
Getting a Collection得到集合
集合(Collection)是MongoDB中的一系列文件,可以理解为关系数据库中的一个表。得到Collection和得到数据库的操作是一样的
collection = db.test_collection
或者collection = db['test-collection']
注:1.从Getting a Database和Getting a Collection中可以看出,你要先得到一个数据库(db是得到的数据库,collection是得到的集合),才能得到数据库中的集合。2.一旦有文档插入的时候集合和数据库就被创建
Documents
MongoDB中的数据都是以JSON的形式存储和展现的,使用PyMongo时是用字典展示文档的
import datetime
post = {
"author": "Mike",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
Inserting a Document插入单个文档
把一个文档插入一个集合中使用 insert_one()
>>> posts = db.posts
#insert_one插入文档,并用inserted_id得到id属性
>>> post_id = posts.insert_one(post).inserted_id
>>> post_id
ObjectId('...')
如果你要插入的文档字典中没有”_id”这个键,它会为你自动生成”_id”键和对应的值,每个文档都有自己特别的id。如图,椭圆中的是每个文档的_id,矩形中的表示一个文档
注:只要插入了第一个文档集合就随之创建通过“数据库名.collection_names()”方法可以查看数据库中所有的集合
>>> db.collection_names(include_system_collections=False)
[u'posts']
访问单个文档
Getting a Single Document With find_one()
得到单个文档的方法find_one(),结果返回None或者相匹配的文档
>>> import pprint
#没有已知信息匹配,返回了刚刚插入的posts
&