1. 用档案管理员做类比
假设我是个档案管理员,我管理一堆档案夹
我选中一个档案夹
然后在其中拿出一本记录
我可以
增 | 删 | 改 | 查 |
---|---|---|---|
![]() | ![]() | ![]() | ![]() |
2. 回到mongodb操作细节
- 选择数据库
use db_name - 选择collection
db.collection.操作函数 - 操作
- 增
db.collection.insertOne(JSON)
db.collection.insertMany(JSONs)
- 删
db.collection.deleteOne(query: JSON)
db.collection.deleteMany(query: JSON)
- 改
db.collection.updateOne(query: JSON,into: JSON)
db.collection.updateMany(query: JSON,into: JSON)
- 查
db.collection.findOne()
db.collection.findOne(query: JSON)
db.collection.find()
db.collection.find(query: JSON)
- 增
- 补充: query条件 --> where 限定符
以id为例
where id = 1
=>{ 'id': 1}
where id > 1
=>{'id': {$gt: 1}}
where id >= 1
=>{'id': {$gte: 1}}
where id < 1
=>{'id': {$lt: 1}}
where id <= 1
=>{'id': {$lte: 1}}
where id != 1
=>{'id': {$ne: 1}}
and
=>{$and: [JSON,JSON,...]}
or
=>{$or: [JSON,JSON,...]}
3. 如何用python调用
- 引入pymongodb
import pymongo
- 连接数据库服务器
client = pymongo.MongoClient(host = 'localhost',port=27017)
- 连接数据库
db = client[db_name]
- 获取collection
col = db[collection_name]
- 操作
- 增
col.insert_one(dict)
col.insert_many([dicts])
- 删
col.delete_one(query: dict)
col.delete_many(query: dict)
- 改
col.update_one(query: dict, into: dict)
col.update_many(query: dict, into: dict)
- 查
col.find_one()
col.find_one(query: dict)
col.find()
col.find(query: dict)
- 增
- 补充
- mongodb的查询query怎么转换到Python语法
特殊符号和JSON键加引号 即可 - 如何查询数据库有哪些
client.list_database_names() -> [str]
- 如何知道collecion有哪些
db.list_collection_names() -> [str]
- mongodb的查询query怎么转换到Python语法