pymongo用法
pymongo是一个用于操作MongoDB数据库的Python库。以下是使用pymongo的基本步骤和示例代码:
1. 安装pymongo库:
```bash
pip install pymongo
```
2. 连接到MongoDB数据库:
```python
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
```
3. 选择数据库和集合:
```python
db = client['my_database']
collection = db['my_collection']
```
4. 插入文档(类似于SQL中的INSERT语句):
```python
document = {"name": "张三", "age": 25, "city": "北京"}
result = collection.insert_one(document)
print("插入成功,文档ID:", result.inserted_id)
```
5. 查询文档:
```python
# 查询所有文档
for doc in collection.find():
print(doc)
# 查询满足条件的文档
query = {"city": "北京"}
for doc in collection.find(query):
print(doc)
```
6. 更新文档:
```python
update_query = {"city": "北京"}
new_values = {"$set": {"city": "上海"}}
result = collection.update_one(update_query, new_values)
print("更新成功,影响文档数:", result.modified_count)
```
7. 删除文档:
```python
delete_query = {"name": "张三"}
result = collection.delete_one(delete_query)
print("删除成功,影响文档数:", result.deleted_count)
```
8. 关闭数据库连接:
```python
client.close()
```