python常用模块-pymongo

主要就是:连接配置 + 增删改查

from pymongo import MongoClient
from data.pwd import mongo_pwd

 

# 命令行模式下,脚本里可适当稍加改动。

# 无需密码的连接
client1 = MongoClient("mongodb://127.0.0.1:27017")
db = client1.school
for student in db.students.find():
print("学号:",student['stu_id'])
db.students.find().count()
db.students.remove()
coll = db.students
coll.insert({"key1":"value1"})
coll.insert_one({"key1":"value1"})
coll.insert_many({"key1":"value1"},{"key1","value2"})

 

# 有密码的连接
host = '127.0.0.1'
client2 = MongoClient(host,27017)
db = client2.admin #偶尔有时不能直接连mydb,可先直连admin,后面再切mydb = client.mydb
db.authenticate("username",mongo_pwd)
# db.authenticate("username",mongo_pwd,mechanism="MONGODB-CR")
# mongodb版本3.0 以后,默认是mechanism="SCRAM-SHA-1";之前的带MONGODB-CR
collection = db.mytest
collection.insert({"key1":"value1"})

 

# 通常可以这样

client = pymongo.MongoClient(host='localhost', port=27017)
db = client.mytest
collection = db.person
res = collection.find_one()

person = { "name": "Mike"}
collection.insert(person)
cur = collection.find()
for c in cur:
print c

condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 25
res = collection.update(condition, student)
res = collection.remove({"name": "Mike"})

 

# 在实际工作中个别关键值,如果经常来回增删或类似按钮的切换,也可以设置is_delete类的键,通过键为True或 False,来定义它的状态。

 

posted @ 2021-03-01 22:46  沈一愣  阅读(96)  评论(0编辑  收藏  举报