python增删改查mongodb
时间: 2023-09-20 10:06:18 浏览: 81
mongodb数据库增删改查
Python操作MongoDB的增删改查方法如下:
1. 连接MongoDB数据库
使用pymongo库连接MongoDB数据库,代码如下:
```python
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
```
2. 插入数据
使用insert_one()或insert_many()方法向MongoDB数据库中插入一条或多条数据,代码如下:
```python
# 插入单条数据
mycollection = db["customers"]
mydict = { "name": "John", "address": "Highway 37" }
x = mycollection.insert_one(mydict)
# 插入多条数据
mylist = [
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"}
]
x = mycollection.insert_many(mylist)
```
3. 查询数据
使用find()方法查询MongoDB数据库中的数据,代码如下:
```python
# 查询所有数据
for x in mycollection.find():
print(x)
# 查询指定数据
myquery = { "address": "Park Lane 38" }
mydoc = mycollection.find(myquery)
for x in mydoc:
print(x)
```
4. 更新数据
使用update_one()或update_many()方法更新MongoDB数据库中的数据,代码如下:
```python
# 更新单条数据
myquery = { "address": "Valley 345" }
newvalues = { "$set": { "address": "Canyon 123" } }
mycollection.update_one(myquery, newvalues)
# 更新多条数据
myquery = { "address": { "$regex": "^S" } }
newvalues = { "$set": { "name": "Minnie" } }
x = mycollection.update_many(myquery, newvalues)
```
5. 删除数据
使用delete_one()或delete_many()方法删除MongoDB数据库中的数据,代码如下:
```python
# 删除单条数据
myquery = { "address": "Mountain 21" }
mycollection.delete_one(myquery)
# 删除多条数据
myquery = { "address": {"$regex": "^S"} }
x = mycollection.delete_many(myquery)
```
阅读全文