pymongo 使用教程
时间: 2023-07-22 20:58:27 浏览: 51
Pymongo 是 Python 语言下操作 MongoDB 数据库的一个非常流行的驱动程序。下面是一个 Pymongo 的简单使用教程。
1. 安装 pymongo
你可以使用 pip 命令安装 pymongo:
```
pip install pymongo
```
2. 连接 MongoDB
在使用 pymongo 操作 MongoDB 数据库之前,你需要先连接 MongoDB。连接 MongoDB 非常简单,只需要使用 pymongo.MongoClient() 方法即可。方法参数为 MongoDB 数据库的地址和端口号。
```python
import pymongo
client = pymongo.MongoClient('localhost', 27017)
```
3. 选择数据库
在连接 MongoDB 成功后,你需要选择要操作的数据库。使用 pymongo 的 client 对象的方法即可选择数据库。
```python
db = client.test_database
```
4. 选择集合
在选择数据库之后,你需要选择要操作的集合。使用数据库对象的属性即可选择集合。
```python
collection = db.test_collection
```
5. 插入文档
在选择集合之后,你可以向集合中插入文档。使用集合对象的 insert_one() 或 insert_many() 方法即可。
```python
post = {
'title': 'Python',
'content': 'Python is a great language.',
'author': 'John Smith'
}
result = collection.insert_one(post)
```
6. 查询文档
你可以使用集合对象的 find() 方法查询集合中的所有文档,也可以使用 find_one() 方法查询集合中的单个文档。
```python
for post in collection.find():
print(post)
post = collection.find_one({'author': 'John Smith'})
print(post)
```
7. 更新文档
你可以使用集合对象的 update_one() 或 update_many() 方法更新集合中的文档。
```python
result = collection.update_one({'author': 'John Smith'}, {'$set': {'content': 'Python is an amazing language.'}})
print(result.matched_count, result.modified_count)
```
8. 删除文档
你可以使用集合对象的 delete_one() 或 delete_many() 方法删除集合中的文档。
```python
result = collection.delete_one({'author': 'John Smith'})
print(result.deleted_count)
```
以上就是 Pymongo 的简单使用教程。更多高级用法可以查看 pymongo 的官方文档。