安装MongoDB 下载(官网https://www.mongodb.com) 安装配置教程(https://juejin.im/post/6844903912000978952) 输入http://localhost:27017,显示如图表示成功
import pymongo client = pymongo.MongoClient(host=‘localhost’, port=27017)
db = client.test
collection = db.students
student1 = { ‘id’: ‘20170101’, ‘name’: ‘Jordan’, ‘age’: 20, ‘gender’: ‘male’ } student2 = { ‘id’: ‘20170201’, ‘name’: ‘Kevin’, ‘age’: 20, ‘gender’: ‘male’ } print("-----插入数据:-----")
result = collection.insert_many([student1, student2]) print(result) print(result.inserted_ids)
print("-----根据名称查询:-----") result = collection.find_one({‘name’: ‘Jordan’}) print(type(result)) print(result)
print("-----多条查询:-----") results = collection.find({‘age’: 20}) print(results) for result in results: print(result)
print("-----正则匹配查询:-----") results = collection.find({‘name’: {’$regex’: ‘^J.*’}}) print(results) for result in results: print(result)
print("-----计数:-----") count = collection.find().count() print(count)
print("-----按名称排序:-----") results = collection.find().sort(‘name’, pymongo.ASCENDING) print([result[‘name’] for result in results])
print("-----偏移:-----") results = collection.find().sort(‘name’, pymongo.ASCENDING).skip(1) print([result[‘name’] for result in results]) print("-----指定结果个数:-----") results = collection.find().sort(‘name’, pymongo.ASCENDING).skip(2).limit(1) print([result[‘name’] for result in results])
print("-----更新:-----") condition = {‘name’: ‘Kevin’} student = collection.find_one(condition) student[‘age’] = 26 result = collection.update_one(condition, {’$set’: student}) print(result) print(result.matched_count, result.modified_count)
print("-----根据名字删除数据:-----") result = collection.remove({‘name’: ‘Jordan’}) print(result)