-
python处理mongodb首选就是pymongo. 首先, 安装一下这个模块
- pip install pymongo
-
建立连接
import pymongo
conn = pymongo.MongoClient(host='localhost', port=27017)
# 切换数据库
py = conn['python']
# 登录该数据库(需要的话)
py.authenticate("python_admin", '123456')
# 简单来个查询
result = py["stu"].find()
for r in result:
print(r)
- 完整代码
import pymongo
from pymongo import MongoClient
def get_db(database, user, pwd):
client = MongoClient(host="localhost", port=27017)
db = client[database]
# 有账号就加上验证, 没有账号就不用验证
db.authenticate(user, pwd)
return db
# 增删改查
# 增加数据
def add_one(table, data):
db = get_db("python", "python_admin", "123456")
result = db[table].insert_one(data)
return result
def add_many(table, data_list):
db = get_db("python", "python_admin", "123456")
result = db[table].insert_many(data_list)
return result.inserted_ids
def upd(table, condition, data):
db = get_db("python", "python_admin", "123456")
data = {'hehe': 'hehe', 'meme': 'meme'}
# result = db[table].update_many(condition, {"$set": data})
result = db[table].update_many(condition, {'$set':data})
return result
def delete(table, condition):
db = get_db("python", "python_admin", "123456")
result = db[table].remove(condition)
return result
if __name__ == '__main__':
# r = add_one("stu", {"name": "西瓜", "age":18})
# print(r.inserted_id)
# r = add_many("stu", [{"name": "嘎嘎"},{"name": "咔咔"}])
# print(r.inserted_ids)
# result = upd("stu", {"name": 99999}, {"age": 100})
# print(result)
result = delete("stu", {"name": "哈哈"})
print(result)
标签:python,MongoDB,数据库,pymongo,db,result,table,data
From: https://www.cnblogs.com/xwltest/p/17365880.html