07-PyMongo 的使用

  • 阅读: 541
  • 更新: 2022-06-11

本文记录 python 中使用 mongodb 的方法
https://pymongo.readthedocs.io/en/stable/tutorial.html

1. 安装

1
pip install pymongo

2. pymongo 的使用

2.1 配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from pymongo import MongoClient

# mongo 配置
MONGO = {
    'host': '127.0.0.1',
    'port': 27017,
    'username': 'root',
    'password': '123456',
    'authSource': 'admin',
}
client = MongoClient(**MONGO)

db = client['test']

2.2 操作整理

操作 语法 描述 示例
查询 find_one 查询单个文档 db.col.find_one({'key': 'value'})
返回 dict 或 None
find 查询所有文档 db.col.find({'key': 'value'})
count_documents 查询满足条件的文档数量 db.col.count_documents({})
插入 insert_one 插入一个文档 db.test.insert_one({'x': 1})
获取插入的id:res.inserted_id
insert_many 插入多个文档 db.test.insert_many([{'x': i} for i in range(2)])
更新 update_one 更新一个文档 db.test.update_one({'x': 1}, {'$inc': {'x': 3}})
update_many 更新所有匹配到的文档 db.col.update_many({'key': 'value'}, {'$set': {'k': 'v'}})
替换 replace_one 替换一个文档 db.test.replace_one({'x': 1}, {'y': 1})
删除 delete_one 删除一个文档 db.test.delete_one({'x': 1})
delete_many 删除所有匹配的文档 db.test.delete_many({'x': 1})
drop 删除表/collection db.foo.drop()
db.drop_collection('foo')

2.3 字符串转为 ObjectId

1
2
from bson import ObjectId
document = client.db.collection.find_one({'_id': ObjectId(post_id)})

2.4 重置游标 cursor

https://pymongo.readthedocs.io/en/stable/api/pymongo/cursor.html#pymongo.cursor.Cursor.rewind

1
2
3
4
res = client['db']['col'].find()
# for r in res:  遍历完之后 res 的长度就为 0 了
# 如果想再次遍历 res,就必须重置游标
res.rewind()

2.5 常用示例代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# $gte 大于等于;$lte 小于等于
res = client['db']['col'].find({
    'month': {'$gte': last_month, '$lte': this_month}
}).sort('month')

# $exists 存在;$ne 不等于
deps = client['db']['col'].find(
        {'name': {'$exists': True, '$ne': None}})

# $in 是否在列表中
res = client['db']['col'].find({
    'username': {'$in': users}})

# limit 和 skip 的使用,常用于分页;sort 排序,-1 倒序
res = client['db']['col'].find().limit(
        page_size).skip((page_number - 1) * page_size).sort(
                [('create_time', -1)])

# $set 更新的字段
client['db']['col'].update_one(
    {'name': name},
    {'$set': {'email': [email]}}
)

# $and 多个条件要同时满足;$ne 不等于
res = client['db']['col'].find_one({
    '$and': [
        {'_id': {'$ne': ObjectId(_id)}},
        {'attribute.name': data['attribute']['name']},
    ]
})

# $regex 正则匹配,相当于 sql 中的 like 语法
querys = [
    {'username': {'$regex': key}},
    {'email': {'$regex': key}},
    {'name': {'$regex': key}},
]
# $or 多个查询条件,匹配其中一条即可;
res = client['db']['col'].find(
        {'$or': querys}).sort([('username', 1)])

# https://www.runoob.com/mongodb/mongodb-aggregate.html
# aggregate 聚合操作;
res = client['db']['col'].aggregate([
    {
        '$match': {  # 用于匹配,相当于 sql 中的 where
            'month': month,
            'name': name,
            }
        },
    {
        '$group': {
            '_id': '$email',  # 分组对象
            'score': {'$sum': '$score'}  # $sum 计算总和
        }
    }
])

=== 全文完 ===


欢迎加入QQ群:855013471

京公网安备 11011302003970号 京ICP备2022012301号-1