首先我们查看我们MongoDB的IP和端口,可以知道是localhost和27017,一般也都是这个,因为如果不给端口传递参数,默认是27017
连接MongoDB
连接时我们需要使用PyMongo库里面的MongoClient并传入MongoDB的IP及端口
法1:
client = pymongo.MongoClient(host='localhost', port=27017)
法2:
client = pymongo.MongoClient('mongodb://localhost:27017/')
选定指定的数据库
选定指定的数据库进行操作,这里我选择test数据库
法1:可以调用client的test属性返回test数据库
db = client.test
法2:
db = client['test']选定指定的集合
MongoDB数据库中的集合就类似于关系型数据库中的表
法1:
collection = db.students
法2:
collection = db['students']插入数据
先设定好要插入的数据
student1 = {
'id': '20225191',
'name': '小蓝',
'age': 8,
'gender': 'male'
}
student2 = {
'id': '20225192',
'name': '小绿',
'age': 9,
'gender': 'male'
}
student3 = {
'id': '20225193',
'name': '小白',
'age': 7,
'gender': 'female'
}
将数据插入到数据库集合中,我们可以一次插入一条数据,也可以一次插入多条数据,这两种的区别是一个是insert_one,一个是insert_many,如果直接用insert的话,有可能不会成功
result1 = collection.insert_one(student1) result2 = collection.insert_many([student2, student3])
查看结果
print(result1) print(result2.inserted_ids)
输出结果:
在MongoDB Compass里面我们也可以看到,新创建了一个test数据库和test集合,集合里面放的正是我们插入的数据,此外如果创建了新的数据库以及新的集合 ,如果集合里面没有插入数据,那么它是不会显示的
完整源码:
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.test
student1 = {
'id': '20225191',
'name': '小蓝',
'age': 8,
'gender': 'male'
}
result1 = collection.insert_one(student1)
student2 = {
'id': '20225192',
'name': '小绿',
'age': 9,
'gender': 'male'
}
student3 = {
'id': '20225193',
'name': '小白',
'age': 7,
'gender': 'female'
}
result2 = collection.insert_many([student2, student3])
print(result1)
print(result2.inserted_ids)
更新数据
连接MongoDB,指定数据库、指定集合
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) db = client.test collection = db.test
找到要修改的数据
condition = {'name': '小蓝'}
student = collection.find_one(condition)
设定要修改的内容
student['age'] = 20
进行修改
法1:指定更新的条件和更新后的数据然后使用update()方法
result = collection.update(condition, student)
法2:使用$set操作符更新数据,只更新student字典内存在的字段,若原先还有其他字段,则不会更新,也不会删除
result = collection.update_one(condition, {'$set': student})查看修改结果
print(result)
print(result.matched_count, result.modified_count)
输出结果:
可以看到小蓝变成了20岁
如果是要更新多条数据就用update_many,这里我要把小绿、小白增加10岁,他们原来是9岁,7岁,现在我要把他们改成19岁、17岁
condition = {'age': {'$lt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 10}})
print(result)
print(result.matched_count, result.modified_count)
结果:
完整源码
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.test
condition = {'name': '小蓝'}
student = collection.find_one(condition)
student['age'] = 20
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)
condition = {'age': {'$lt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 10}})
print(result)
print(result.matched_count, result.modified_count)
查找数据
查找一条数据用find_one
result = collection.find_one({'name': '小蓝'})
print(type(result))
print(result)
结果
查找多条数据用find_many
results = collection.find({'age': {'$lt': 20}})
print(results)
for result in results:
print(result)
结果
上面我们根据名字,年龄进行了查询,还可以根据id进行查询,这里要引用bson库
from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('6285c1f47b2657d552e77384')})
print(result)
结果
完整源码
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.test
result = collection.find_one({'name': '小蓝'})
print(type(result))
print(result)
results = collection.find({'age': {'$lt': 20}})
print(results)
for result in results:
print(result)
from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('6285c1f47b2657d552e77384')})
print(result)
计数
因为我的MongoDB版本是V5.0.7,count方法已经不适用,所以采用count_documents
记总的记录数
count = collection.count_documents({})
print(count)
记符合条件的记录数
count = collection.count_documents({'age': 20})
print(count)
结果
完整源码
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.test
count = collection.count_documents({})
print(count)
count = collection.count_documents({'age': 20})
print(count)
排序
使数据升序
results = collection.find().sort('age', pymongo.ASCENDING)
print([result for result in results])
结果
降序就将ASCENDING换成DESCENDING
结果
完整源码:
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.test
results = collection.find().sort('age', pymongo.ASCENDING)
print([result for result in results])
results = collection.find().sort('age', pymongo.DESCENDING)
print([result for result in results])
偏移
偏移一位
results = collection.find().sort('name', pymongo.ASCENDING).skip(1)
print([result['name'] for result in results])
偏移两位
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
搭配limit使用,只取限定数量
results = collection.find().sort('name', pymongo.ASCENDING).skip(1).limit(1)
print([result['name'] for result in results])
结果
完整源码
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.test
results = collection.find().sort('name', pymongo.ASCENDING).skip(1)
print([result['name'] for result in results])
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
results = collection.find().sort('name', pymongo.ASCENDING).skip(1).limit(1)
print([result['name'] for result in results])
删除数据
使用delete_one删除一条数据,使用delete_many删除多条数据:
result = collection.delete_one({'name': '小蓝'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 20}})
print(result.deleted_count)
结果
删除集合
collection.drop()
结果
完整源码
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.test
result = collection.delete_one({'name': '小蓝'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 20}})
print(result.deleted_count)
collection.drop()
关闭连接
Client.close()



