一、缘由
这是之前学习的时候写下的基础代码,包含着MongDB数据库和Python交互的基本操作。
二、代码实现
import pymongo #连接数据库 client=pymongo.MongoClient(host='localhost',port=27017) #制定数据库 db=client.test #指定或生成文档集合 collection=db.students ''' 插入数据 ''' #在文档集合里面插入一条数据 student={ 'id':'20170101', "name":"Jordan", "gender":"male" } result=collection.insert_one(student) print(result) #在集合里面插入多条数据 student1={ 'id':'20170101', "name":'Jordan', "gender":'male' } student2={ 'id':'20170202', 'name':'Mike', 'age':21, "gender":'male' } result=collection.insert_many([student1,student2]) print(result) ''' 查询 ''' # result=collection.find_one({'name':'Mike'}) # print(result) # results=collection.find({'name':{"$gt":20}}) # print(results) # for result in results: # print(result) ''' 计数 ''' count=collection.count_documents({'age':{"$gt":20}}) print(count) ''' 排序 ''' results=collection.find().sort('name',pymongo.ASCENDING) for result in results: print(result['name'] ) ''' 偏移 ''' #跳过 results=collection.find().sort('name',pymongo.ASCENDING).skip(2) print([result['name'] for result in results]) #限制 results=collection.find().sort('name',pymongo.ASCENDING).limit(2) print([result['name'] for result in results]) ''' 更新 ''' condition={'name':'Mike'} students={"$set":{'age':26}} result=collection.update_many(condition,students) print(result.modified_count) results=collection.find() print([result for result in results])