pymongo基本操作
时间: 2024-03-30 10:14:19 浏览: 61
python使用pymongo与MongoDB基本交互操作示例
好的,下面是 pymongo 的一些基本操作:
1. 连接 MongoDB 数据库
```python
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
```
2. 创建或选择数据库
```python
db = client['mydatabase']
```
3. 创建或选择集合
```python
collection = db['mycollection']
```
4. 插入一条数据
```python
data = {"name": "John", "age": 25}
collection.insert_one(data)
```
5. 插入多条数据
```python
data_list = [
{"name": "John", "age": 25},
{"name": "Mary", "age": 30},
{"name": "Tom", "age": 35}
]
collection.insert_many(data_list)
```
6. 查询一条数据
```python
query = {"name": "John"}
result = collection.find_one(query)
```
7. 查询多条数据
```python
query = {"age": {"$gt": 30}}
result = collection.find(query)
for data in result:
print(data)
```
8. 更新一条数据
```python
query = {"name": "John"}
new_data = {"$set": {"age": 26}}
collection.update_one(query, new_data)
```
9. 更新多条数据
```python
query = {"age": {"$lt": 30}}
new_data = {"$set": {"age": 30}}
collection.update_many(query, new_data)
```
10. 删除一条数据
```python
query = {"name": "John"}
collection.delete_one(query)
```
11. 删除多条数据
```python
query = {"age": {"$gt": 30}}
collection.delete_many(query)
```
以上就是 pymongo 的一些基本操作,希望能对你有所帮助。
阅读全文