>>> import pymongo #导入模块
>>> client = pymongo.MongoClient('localhost', 27017) #连接服务器
>>> db = client.teacher #连续数据库
>>> teacher = db.teacher #数据集
>>> list(teacher.find()) #查看已有记录
[]
>>> wangwu = {'name':'Wangwu', 'age':40, 'sex':'male'}
>>> teacher.insert(wangwu) #插入数据
ObjectId('5736992446bf3d29e441c594')
>>> zhangsan = {'name':'Zhangsan', 'age':38, 'sex':'male'}
>>> teacher.insert(zhangsan)
ObjectId('57369aea46bf3d29e441c595')
>>> lisi = {'name':'Lisi', 'age':39, 'sex':'male', 'addr':'Shandong'} #同一个数据库的每条记录之间字段个数可以不一样
>>> teacher.insert(lisi)
ObjectId('57369b1846bf3d29e441c596')
>>> for item in teacher.find(): #列出数据库中的所有记录
print(item)
{'age': 40, 'name': 'Wangwu', '_id': ObjectId('5736992446bf3d29e441c594'), 'sex': 'male'}
{'age': 38, 'name': 'Zhangsan', '_id': ObjectId('57369aea46bf3d29e441c595'), 'sex': 'male'}
{'age': 39, 'name': 'Lisi', 'addr': 'Shandong', '_id': ObjectId('57369b1846bf3d29e441c596'), 'sex': 'male'}
>>> teacher.find().count() #记录条数
3
>>> teacher.update({'name':'Zhangsan'},{'$set':{'age':25}}) #更新记录
{'n': 1, 'nModified': 1, 'ok': 1, 'updatedExisting': True}
>>> for item in teacher.find():
print(item)
{'age': 40, 'name': 'Wangwu', '_id': ObjectId('5736992446bf3d29e441c594'), 'sex': 'male'}
{'age': 25, 'name': 'Zhangsan', '_id': ObjectId('57369aea46bf3d29e441c595'), 'sex': 'male'}
{'age': 39, 'name': 'Lisi', 'addr': 'Shandong', '_id': ObjectId('57369b1846bf3d29e441c596'), 'sex': 'male'}
>>> teacher.remove({'name':'Wangwu'}) #删除一条记录,如果没有参数则表示清空数据库
{'n': 1, 'ok': 1}
>>> teacher.remove({'name':'Wangwu'})
{'n': 0, 'ok': 1}
>>> teacher.find().count()
2