使用PyMongo连接MongoDB的基本操作
MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档、数组及文档数组。在这一节中,我们就来回顾Python 3下MongoDB的存储操作。
常用命令:
-  查询数据库: show dbs
-  使用数据库: use 库名
-  查看集合: show tables/show collections
-  查询表数据: db.集合名.find()
-  删除表: db.集合名.drop()
链接MongoDB
 
连接MongoDB时,我们需要使用PyMongo库里面的MongoClient。一般来说,传入MongoDB的IP及端口即可,其中第一个参数为地址host,第二个参数为端口port(如果不给它传递参数,默认是27017)
    import pymongo # 如果是云服务的数据库 用公网IP连接client = pymongo.MongoClient(host='localhost', port=27017)指定数据库与表
    import pymongoclient = pymongo.MongoClient(host='localhost', port=27017)collection = client['students']
插入数据
对于students这个集合,新建一条学生数据,这条数据以字典形式表示:
    # pip install pymongoimport pymongomongo_client = pymongo.MongoClient(host='localhost', port=27017)collection = mongo_client['students']['stu_info']# 插入单条数据# student = {'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}# result = collection.insert_one(student)# print(result)# 插入多条数据student_1 = {'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}student_2 = {'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}result = collection.insert_many([student_1, student_2])print(result)