python操控MongoDB(增删查改基本操作)

MongoDB简介

MongoDB数据库是一种开源的跨平台的数据库,主要特点如下:

  • 数据存储没有模式:每个文档的模式可以不同,不仅数据类型可以不同,结构也可以不同
  • 具有很强的容易扩展性:文档数据可以被自动分割处理
  • 支持高并发书写:集群提高读写性能,甚至可以建立读写分享的集群服务器
  • 支持海量存储:内置GridFS,支持大容量的分布式存储。

python操作MongoDB基本步骤

  • 导入pymongo库
  • 用pymongo.MongoClient类连接数据库
  • 用pymongo.MongoClient实例选择使用指定的数据库生成数据库对象
  • 用数据库对象生成集合对象,之后就可以用这个对象来操作数据库了

例子:python操作mongodb中学生表实例,演示增删查改

实验效果
在这里插入图片描述

实验代码:

from pymongo import MongoClient

def output_all():
    stu = collection.find()
    for item in stu:
        print(item)
if __name__ == '__main__':
    print('建立连接...')
    client = MongoClient(host='localhost',port=27017)
    db = client.test
    collection = db.students
    students = {'id':'20170101','name':'john','age':20,'gender':'male'}
    students1 = {'id':'20170102','name':'Amy','age':20,'gender':'male'}
    students2 = {'id':'20170103','name':'Linda','age':20,'gender':'male'}
    # 每次运行清空表
    print('清空表信息.....')
    collection.drop()
    # 插入信息
    collection.insert_one(students)
    collection.insert_many([students1,students2])
    stu = collection.find()
    # 查找全部
    output_all()

    print('查找叫做john的....')
    # 查询叫做john的
    stu = collection.find({'name':'john'})

    for item in stu:
        print(item)
    print('删除叫做john...')
    stu = collection.delete_one({'name': 'john'})
    stu = collection.find()
    output_all()
    # 修改名字将Amy修改为Anna
    print('修改Amay叫做Anna...')
    collection.update_one({'name':'Amy'},{'$set':{'name':'Anna'}})
    stu = collection.find()
    output_all()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章