python调用数据库基本操作(pymongo)
mongo DB
>>> pymongo
非关系型数据库利用键值对
存取数据,性能较高
操作 pymongo
库
如何创建?
pymongo
库的操作基于mongoDB
若一次插入多条数据,可用collection.insert_many([student1, student2])
传入JSON格式数据,一旦插入,就自动添加_id字段
在一切开始之前要先连接数据库,指定数据库和集合(表)
import pymongo
client = pymongo.MongoClient(host="localhost", port=27017)
## 指定数据库
db = client.test
# 指定集合(类似于表)
collection = db.students
# 插入数据
student = {
"id": "10001",
"name": "Jordan",
"age": "20",
"gender": "male"
}
result = collection.insert_one(student)
查询并依次打印
字典 >>> 等式选择
字典里面套字典 >>> 不等式选择
这个查询结果是生成器,必须要循环
results = collection.find({"age":{"$gte":20}})
for result in results:
print(result)
符号 | 含义 |
---|---|
$lt | 小于 |
$gt | 大于 |
$lte | 小于等于 |
$gte | 大于等于 |
$ne | 不等于 |
$in | 在···范围内 |
$nin | 不在···内{"age": {"$nin": [20, 23]}} |
其他例子
results = collection.find({"name":{"$regex": "^C.*"}})
符号 | 例子 | 含义 |
---|---|---|
$regex | {“name”: {“$regex”: “^C.*”}} | 以C开头的名字 |
$exists | {“name”: {“$exists”: True}} | 名字属性存在 |
$type | {“age”: {“$type”: “Int”}} | age的类型为Int |
$mod | {“age”: {“$mod”: “[5, 0]”}} | 年龄是5的倍数 |
$text | {“$text”: {“$search”: “Mike”}} | text类型的属性中包含Mike的字符串 |
$where | {“$where”: “obj.fans_count=obj.follows_count”} | 自身粉丝数等于关注数 |
计数
.count()
计数方法
result = collection.find().count()
排序
.sort()
方法
result = collection.find().count().sort("name", pymongo.ASCENDING)
偏移与输出限制
.skip()
方法
.limit()
方法
# .skip(2)忽略第1、2个结果
# .limit(2)只取前两个结果
results = collection.find().count().sort("name", pymongo.ASCENDING).skip(2).limit(2)
更新
先找到,然后更新属性,再插回去
update_many()
: 更新全部(常用)
update_one()
: 只更新第一条
{"$set": student}
: 只改字典student内的字段
condition = {"name": "Claire"}
student = collection.find_one(condition)
student["age"] = "25"
result = collection.update_one(condition, {"$set":student})
print(result)
删除
condition = {"name": "Claire"}
result = collection.delete_one(condition)
print(result)