在Python中使用MongoDB,您需要先安装`pymongo`库,然后通过`pymongo`连接到MongoDB数据库,并执行各种操作,如插入、查询、更新和删除数据。以下是使用`pymongo`操作MongoDB的基本步骤:
1. 安装`pymongo`库:
pip install pymongo
2. 连接到MongoDB数据库:
from pymongo import MongoClient连接到本地MongoDB服务器client = MongoClient('mongodb://127.0.0.1:27017/')选择数据库db = client['database_name']选择集合(表)collection = db['collection_name']
3. 插入数据:
插入一条数据insert_result = collection.insert_one({'name': 'John Doe', 'age': 30, 'city': 'New York'})print(f"Inserted document with ID: {insert_result.inserted_id}")插入多条数据docs = [{'name': 'Jane Doe', 'age': 28, 'city': 'Los Angeles'},{'name': 'Mike Smith', 'age': 35, 'city': 'Chicago'}]collection.insert_many(docs)

4. 查询数据:
查询所有文档for document in collection.find():print(document)查询特定文档result = collection.find_one({'name': 'John Doe'})print(result)使用排序和限制返回结果数量last_document = collection.find().sort('_id', -1).limit(1)print(last_document)
5. 更新数据:
更新一条数据update_result = collection.update_one({'name': 'John Doe'}, {'$set': {'age': 31}})print(f"Modified count: {update_result.modified_count}")更新多条数据update_result = collection.update_many({'city': 'New York'}, {'$set': {'city': 'Los Angeles'}})print(f"Modified count: {update_result.modified_count}")
6. 删除数据:
删除一条数据delete_result = collection.delete_one({'name': 'John Doe'})print(f"Deleted count: {delete_result.deleted_count}")删除所有数据delete_result = collection.delete_many({})print(f"Deleted count: {delete_result.deleted_count}")
以上步骤展示了如何使用`pymongo`在Python中执行基本的数据库操作。您可以根据需要调整查询、更新和删除的条件。
