1.下载mongo的驱动模块:python -m pip install pymongo
2.创建连接,指定数据库,指定集合
#mongoDB
import pymongo
client=pymongo.MongoClient('mongodb://localhost:27017')
client
#指定数据库
db=client.test
db
#指定集合
collection=db.students
collection
3.插入数据
#插入数据
student={
'id':'2',
'name':'sp',
'age':22,
'gender':'male'
}
result=collection.insert_one(student)
print('_id:',result.inserted_id)
#插入多条数据
student2={
'id':'2',
'name':'pp',
'age':22,
'gender':'male'
}
student3={
'id':'2',
'name':'mm',
'age':22,
'gender':'male'
}
result=collection.insert_many([student2,student3])
id2=result.inserted_ids[1]
print('_id:',result.inserted_ids)
4.查询
#查询
result=collection.find_one({'name':'sp'})
print(type(result))
print(result)
#根据 _id查询
result=collection.find_one({'_id':id2})#id2是前面定义的一个对象
print(type(result))
print(result)
#查询多条数据
results=collection.find({'age':22})
print(results)
for result in results:
print(result)
#更多条件查询
# $lt < $gt > $lte <= $gte >= $ne != $in $nin
results=collection.find({'age':{'$gte':20}})
for result in results:
print(result)
# 正则表达式查询 $regex 更多功能符号: $exists $type $mod $text $where
results=collection.find({'name':{'$regex':'^s.*'}})#表示以s开头
for result in results:
print(result)
5.计数,排序,偏移(用于分页)
#计数
count=collection.find().count()
print(count)
##排序
results=collection.find().sort('name',pymongo.ASCENDING)
print([result['name'] for result in results])
#偏移 用于分页
results=collection.find().sort('name',pymongo.ASCENDING).skip(4).limit(2)
for result in results:
print(result)
6.更新
#更新
condition={'name':'sp','age':22} #条件
student1={}
student1['age']=25
result=collection.update_many(condition,{'$set':student1})
print(result.matched_count, result.modified_count)
7.删除
#删除
result=collection.delete_one({'name':'sp'})
print(result.deleted_count)
#按指定删除多个
result=collection.delete_many({'age':{'$lte':25}})
print(result.deleted_count)