Python中MongoDB的连接与增删改查操作

导包

import pymongo    

若没有该模块,进入cmd, pip install pymongo

连接mongodb

mongoclient = pymongo.MongoClient("localhost",port=27017)

localhost表示本机ip,也可以用回环地址127.0.0.1 ,或者用自己的服务器地址, 而mongodb默认port是27017

创建数据库

db = mongoclient .className

使用/创建库,存在则使用,不存在则创建,只有插入数据之后才可查看,className是你的数据库名

创建集合

collection = db.students

集合 = 库.集合名

数据操作

插入一条

collection.insert({"name":"胖子","age":18})
或者
collection.save({"name":"胖子","age":18})

插多条

扫描二维码关注公众号,回复: 2778507 查看本文章
collection.insert([{"name":"奥巴马","age":30},{"name":"李健","gender":1}])

查找

collection.find({"name":"胖子"},{"name":1,"age":1})
或者
collection.find("_id":ObjectId("...."))
或者
collection.find_one({"name":"胖子"})

find第一个参数表示条件,第二个表示结果显示内容,后者需要导入ObjectId模块

排序

按age逆序

collection.find().sort("age":-1)

分页

collection.find().skip(2).limit(1)

跳过两条语句,获取一条语句

遍历获取结果

res = collection.find()

for data in res:

   print(data)

修改/更新

collection.update({"age":18},{"$set":{"age":12}},multi=True)

删除一条

collection.remove({"age":18}, multi = False)

删除name=lisi的某个id的记录

id = my_set.find_one({"name":"胖子"})["_id"]
collection.remove(id)

删除所有符合条件

collection.remove({"age":18})

删除集合里的所有记录

db.collection.remove()

猜你喜欢

转载自blog.csdn.net/Lq_520/article/details/81662524