MongoDB数据库

pymongo安装

  1. pip install pymongo

连接数据库

  1. 方式一
  2. client = MongoClient()
  3. 方式二 指定端口和地址
  4. client = MongoClient('localhost',27017)

新增数据

  1. from pymongo import MongoClient
  2. from datetime import datetime
  3. class TestMongo(object):
  4. def __init__(self):
  5. self.client = MongoClient('mongodb://localhost:27017/')
  6. # 也可以指定连接的集合client['admin']['students']
  7. self.db = self.client['admin']
  8. # print(self.client.database_names())
  9. def add_one(self):
  10. post = {'title':'标题','content':'内容','created_at':datetime.now()}
  11. # db.students students 是表明
  12. res = self.db.students.insert_one(post)
  13. return res
  14. def add_more(self):
  15. data_list = [{"name":"test{}".format(i)} for i in range(5)]
  16. res = self.db.students.insert_many(data_list)
  17. return res
  18. mongo = TestMongo()
  19. res = mongo.add_one()
  20. 插入的ID
  21. print(res.inserted_id)

查询数据

  1. from bson.objectid import ObjectId
  2. 查询一条数据
  3. def get_one(self):
  4. return self.db.students.find_one()
  5. 查询多条数据
  6. def get_more(self):
  7. return self.db.students.find()
  8. 根据记录的ID查询数据
  9. def get_from_id(self,id):
  10. return self.db.students.find_one({'_id':ObjectId(id)})
  11. 查询一条数据
  12. res = mongo.get_one()
  13. 查询多条数据
  14. res = mongo.get_more()
  15. for i in res:
  16. print(i)
  17. 根据记录的ID查询数据
  18. res = mongo.get_from_id('5b83e8a1b594c32e8c70c1f7')
  19. print(res)

修改数据

  1. 修改单条数据
  2. def update(self):
  3. res = self.db.students.update_one({'title':'标题'},{'$set':{'title':'title-2'}})
  4. # 匹配的数据条数
  5. print(res.matched_count)
  6. # 影响的数据条数。
  7. print(res.modified_count)
  8. 修改多条
  9. def update_more(self):
  10. res = self.db.students.update_many({},{'$set':{'x':1}})
  11. print(res.matched_count)
  12. print(res.modified_count)
  13. res = self.db.students.update({'x':2},{'$set':{'x':3}},True)
  14. res = mongo.update()
  15. res = mongo.update_more()

删除数据

  1. 删除一条
  2. def delete_one(self):
  3. res = self.db.students.delete_one({'title':'title-2'})
  4. print(res.deleted_count)
  5. 删除多条
  6. def delete_more(self):
  7. res = self.db.students.delete_many({'x':2})
  8. print(res.deleted_count)
  9. res = mongo.delete_one()
  10. res = mongo.delete_more()