MongoDB 文档操作与聚合操作
warning:
这篇文章距离上次修改已过185天,其中的内容可能已经有所变动。
from pymongo import MongoClient
# 连接到MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['test_database'] # 选择数据库
collection = db['test_collection'] # 选择集合
# 插入文档
doc1 = {'name': 'Alice', 'age': 25, 'address': {'city': 'New York', 'country': 'USA'}}
collection.insert_one(doc1)
# 查询文档
query = {'name': 'Alice'}
result = collection.find_one(query)
print(result)
# 更新文档
update_query = {'name': 'Alice'}
update = {'$set': {'age': 28}}
collection.update_one(update_query, update)
# 删除文档
delete_query = {'name': 'Alice'}
collection.delete_one(delete_query)
# 聚合操作
aggregation_pipeline = [
{'$match': {'address.city': 'New York'}},
{'$group': {'_id': '$address.city', 'num_people': {'$sum': 1}}}
]
result = collection.aggregate(aggregation_pipeline)
for doc in result:
print(doc)
这段代码展示了如何在Python中使用pymongo库连接到MongoDB,并执行基本的文档操作(插入、查询、更新、删除)以及聚合查询。这对于理解如何在实际应用中使用MongoDB非常有帮助。
评论已关闭