Working with MongoDB and Pymongo

MongoDB的学习详见 官方文档 或者 我的博客

运行环境: + Pymongo 3.7.2

准备工作

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

# 创建客户端对象,连接数据库
client = pymongo.MongoClient('localhost',27017)

# 链接数据库
db = client.dbname
db = client['dbname']

# 获取数据库中的集合
collection = db.collectionname
collection = db['collectionname']

一、添加记录Create

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
# 语法同 MongoDB
# insert_one()
# insert_many()
# insert() 官方已不推荐使用,但可以用

student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}

result = collection.insert_one(student1)
print(result)
# <pymongo.results.InsertOneResult object at 0x10d68b558>
print(result.inserted_id)
# 5932ab0f15c2606f0c1cf6c5

result = collection.insert_many([student1, student2])
print(result)
# <pymongo.results.InsertManyResult object at 0x101dea558>
print(result.inserted_ids)
#[ObjectId('5932abf415c2607083d3b2ac'),ObjectId('5932abf415c2607083d3b2ad')]

二、查找记录Find

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 语法同 MongoDB
# find_one()
# find()

result = collection.find_one({'name': 'Mike'})
print(type(result))
#<class 'dict'>
print(result)
#{'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}


results = collection.find({'age': 20})
print(results)
# <pymongo.cursor.Cursor object at 0x1032d5128>
for result in results:
print(result)
"""
{'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('593278c815c2602678bb2b8d'), 'id': '20170102', 'name': 'Kevin', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('593278d815c260269d7645a8'), 'id': '20170103', 'name': 'Harden', 'age': 20, 'gender': 'male'}
"""
# 返回结果是Cursor类型,相当于一个生成器,我们需要遍历取到所有的结果,每一个结果都是字典类型。

还有一些其他函数如下

1
2
3
4
5
6
7
8
# 计数
count = collection.find().count()
# 排序
results = collection.find().sort('name',pymongo.ASCENDING)
# 偏移
results = collection.find().sort('name',pymongo.ASCENDING).skip(2)
# 限制个数
results = collection.find().sort('name',pymongo.ASCENDING).skip(2).limit(2)

三、更新记录Update

1
2
3
4
5
6
7
8
9
10
11
# 语法同 MongoDB
# update_one()
# update_many()
# update() 官方已不推荐使用,但可以用

condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
# <pymongo.results.UpdateResult object at 0x10c6384c8>
print(result.matched_count, result.modified_count)
# 3 3

四、删除记录Remove

1
2
3
4
# 语法同 MongoDB
# delete_one()
# delete_many()
# remove()

参考链接:

  • https://www.jb51.net/article/119823.htm
  • http://api.mongodb.com/python/current/api/pymongo/collection.html