MongoDB与Python交互

MongoDB与Python交互

一、准备工作

要实现MongoDB与Python交互操作,必须安装pymongo模块,查看pymongo官方文档

pip3 install pymongo

MongoDB与Python交互

二、连接MongoDB

import pymongo

无认证连接:client = pymongo.MongoClient("mongodb://host:port/dbname")

有认证连接:client = pymongo.MongoClient("mongodb://username:password@host:port/dbname")

MongoDB与Python交互

三、指定数据库与集合

db = client.school

collection = db.class02

MongoDB与Python交互

四、插入数据

插入单条数据:collection.insert_one({字典})

插入多条数据:collection.insert_many([{字典1},{字典2},...])

 MongoDB与Python交互

MongoDB与Python交互

五、更新数据

更新单条数据:collection.update_one({条件},{"$set":{要更新的键:要更新的值}})

更新多条数据:collection.update_many({条件},{"$set":{要更新的键:要更新的值}})

 MongoDB与Python交互

MongoDB与Python交互

六、删除数据

删除单条数据:collection.delete_one({条件})

删除多条数据:collection.delete_many({条件})

MongoDB与Python交互

MongoDB与Python交互

七、查询数据

 查询单条数据:collection.find_one({条件}),返回的是一个字典

查询单条或多条数据:collection.find({条件}),返回的是一个迭代器

MongoDB与Python交互

MongoDB与Python交互

对查询结果进行排序:collection.find({条件}).sort("字段",pymongo.ASCENDING) 或 collection.find({条件}).sort("字段",1)

对查询结果进行偏移:collection.find({条件}).skip(n),n表示偏移数量

对查询结果进行限制:collection.find({条件}).limit(n),n表示限制数量

MongoDB与Python交互

MongoDB与Python交互

MongoDB与Python交互