连接:

client = MongoClient(’mongodb://localhost:27017/')

指定数据库:

db = client.test

指定集合:

collection = db.students

增:

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

// 单条
result = collection.insert_one(studentl)
print(result)
print(result.inserted_ids)
// 运行结果如下:
<py mongo.results.InsertManyResult object at ox101deaSS8>
5932abf415c2607083d3b2ac

// 多条
result = collection.insert_many([studentl, student2])
print(result)
print(result.inserted_ids)
// 运行结果如下:
<py mongo.results.InsertManyResult object at ox101deaSS8>
[Objectid ('5932abf415c2607083d3b2ac'), Objectid('5932abf415c2607083d3b2ad')]

删:

result = collection.delete_one({'name': 'Mike'}) // 删1条
result = collection.delete_many({'age': {'$gt': 20}}) // 删多条
print(result.deleted count) // 删掉的条数

改:

condition = {'age': {'$gt': 20}} // 查询条件
// 查询后将第一个的age改为26
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})
// 改多条,查询后所有的age加1
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result.matched_count, result.modified_count) // 匹配条数、影响条数

查:

// 查单条
result = collection.find_one({'name': 'Mike'})
// 查多条
result = collection.find({'age': 20})
// 查id
from bson.objectid import Objectid
result = collection.find({'_id': Objectid('593278c11Sc2602667ec6bae')})
// 查条件
result = collection.find({'age': {'$gt': 20}}) // 大于20的
// 正则查
result = collection.find({'name': {'$regex': '^M.*'}}) // name是M开头的
// 查计数
count = result.count()
// 排序
sortList = result.sort('name', pymogo.ASCENDING) // 若降序:DESCENDING
// 偏移
results = result.skip(2) // 从前偏移2,从第三个及以后开始取
results = result.limit(2) // 取前两个结果
print(type(result))
print(result)
// 结果
<class 'dict'>
[{
'_id': Objectld('593278c11Sc2602667ec6bae'),
'id': '20170101',
'name': 'Jordan',
'age': 20, 'gender':
'male'
}]

Python-MongoDB 笔记(增删改查)_mogodb

Python-MongoDB 笔记(增删改查)_mogodb_02

更详细用法, 可以在MongoDB 官方文档找到:

MongoDB 官方文档

​​

​​​​​

其他操作
另外,PyMongo 还提供了一些组合方法,如find_one_and_ delete()、find_one_and_replace ()和find_one_and_update(),它们是查找后删除、替换和更新操作,其用法与上述方法基本一致。
另外,还可以对索引进行操作,相关方法有create_index()、create_indexes()和drop_index()等。

关于PyMongo 的详细用法,可以参见官方文档:

PyMongo 的详细用法

​​

​​​​​

另外,还有对数据库和集合本身等的一些操作,这里不再一一讲解,可以参见官方文档:

PyMongo 官方文档

​​

​​​​​

觉得有用的小伙伴,记得点个赞鼓励一下~

      ☟