python mongodb更新数据
时间: 2023-10-13 16:24:23 浏览: 48
在 MongoDB 中,更新数据可以使用 `update_one()` 或 `update_many()` 方法。
`update_one()` 方法可以用来更新集合中的单个文档,语法如下:
```python
collection.update_one(filter, update, upsert=False)
```
参数说明:
- `filter`:更新筛选条件,类似 SQL 中的 WHERE 子句。
- `update`:更新操作,可以是一个字典或 MongoDB 更新操作符。
- `upsert`:可选参数,如果设置为 True,当更新条件不存在时会插入一条新记录。
示例代码:
```python
from pymongo import MongoClient
client = MongoClient()
db = client['mydb']
collection = db['mycollection']
# 更新单个文档
filter = {'name': 'Alice'}
update = {'$set': {'age': 20}}
result = collection.update_one(filter, update)
print(result.modified_count) # 输出修改的记录数
```
`update_many()` 方法可以用来更新集合中的多个文档,语法如下:
```python
collection.update_many(filter, update)
```
参数说明同 `update_one()` 方法,示例代码:
```python
from pymongo import MongoClient
client = MongoClient()
db = client['mydb']
collection = db['mycollection']
# 更新多个文档
filter = {'gender': 'male'}
update = {'$set': {'age': 30}}
result = collection.update_many(filter, update)
print(result.modified_count) # 输出修改的记录数
```