mongodb数据库
可以在官方下载
导入
import pymongo
# 创建一个连接对象
client = pymongo.MongoClient(
host="127.0.0.1",
port=27017
)
# 找到一个数据库 class是数据库名
db = client['class']
# 第二种方法找到一个数据库:
db = client.class # class是数据库名
# 找到数据库中对应的表 students是表名
collection = db["students"]
# 第二种方法找到数据库中对应的表
collection = db.students # students是表名
增加数据:
# 构造插入数据
student = {
"carid":"20171611843",
"name":"jok",
"age":3,
"gender":"male"
}
# 构造多条数据
student1 = {...} ...
# 插入数据 insert方法快要被淘汰掉了
result = collection.insert_one(student) #插入一条数据
# 插入多条数据 用列表存储数据变量
result = collection.insert_many([student2,student3,student4])
更新数据:
update方法:旧版本的方法,不推荐使用
replace_one方法:可以使用
update_one方法:暂时不能用
student = collection.find_one({"name":"小卤蛋"})
student["age"] = 25
# 将修改后的数据传入数据库的表中
result = collection.replace_one({"name":"小卤蛋"}, student)
update_many方法:
# 更新
condition = {"age":{"$gt":3}} # 写一个公共的规则
client = pymongo.MongoClient(
host="127.0.0.1",
port=27017
)
db = client["class"]
collection = db["students"]
# 根据(condition)比三岁大的条件,每条数据都累加1
s = collection.update_many(condition,{"$inc":{"age":1}})
删除数据:
delete_one方法 : 移除一条
delete_many方法 : 移除多条
res = collection.delete_one({"name":"jok"})
print(res)
# 移除比40岁大的
res2 = collection.delete_many({"age":{"$gt":40}})
print(res2)
查找数据:
find方法:
1、返回的类型是对象类型
2、如果有多条数据同时满足条件,则会找到全部的数据,但拿取数据的时候需要通过遍历的方式来打印
3、数据打印直接print就可以
4、过滤时要用符号表示:
# 找到一个 name=jok 的数据
# 返回的是ID
res1 = collection.find({"name":"jok"})
# 查看表中有多少数据
count = collection.find().count_documents({}) # 字典中可以传入过滤信息
# 找到符合要求的数据
filter1 = find({"age":{"$gt":30}}) #查找年龄大于三十岁的
# 还可以用来排序 给指定属性进行排序
sortNum = find().sort("name",pymongo.ASCENDING)#升序排序
sortNum = find().sort("name",pymongo.DESCENDING)#降序排序
find_one方法:
1、返回的是字典类型 键值对
2、如果有多条数据同时满足条件,则只返回找到的第一条
# 找到一个name = jok 的数据
# 返回的是字典类型
res2 = collection.find_one({"name":"jok"})
find_many方法:可以找到多条数据
偏移:
# 偏移
res6 = collection.find().sort("age",pymongo.ASCENDING).skip(2)
#偏移两个
print([res["name"] for res in res6])