Python+MongoDB 实战练习

it2024-12-27  11

1.准备工作

安装MongoDB 下载(官网https://www.mongodb.com) 安装配置教程(https://juejin.im/post/6844903912000978952) 输入http://localhost:27017,显示如图表示成功

2.连接 MongoDB

import pymongo client = pymongo.MongoClient(host=‘localhost’, port=27017)

client = MongoClient(‘mongodb://localhost:27017/’)

3.指定数据库

db = client.test

4.指定集合

collection = db.students

5.插入数据

student1 = { ‘id’: ‘20170101’, ‘name’: ‘Jordan’, ‘age’: 20, ‘gender’: ‘male’ } student2 = { ‘id’: ‘20170201’, ‘name’: ‘Kevin’, ‘age’: 20, ‘gender’: ‘male’ } print("-----插入数据:-----")

result = collection.insert_one(student)

result = collection.insert_many([student1, student2]) print(result) print(result.inserted_ids)

6.查询

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)

7.计数

print("-----计数:-----") count = collection.find().count() print(count)

8.排序

print("-----按名称排序:-----") results = collection.find().sort(‘name’, pymongo.ASCENDING) print([result[‘name’] for result in results])

9.偏移

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])

10.更新

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)

11.删除

print("-----根据名字删除数据:-----") result = collection.remove({‘name’: ‘Jordan’}) print(result)

最新回复(0)