python连接mongoDB,进行增删改查操作

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)

参考文档:https://api.mongodb.com/python/3.4.0/

                  https://docs.mongodb.com/manual/reference/operator/query/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值