使用python操作Mongo数据库,包括连接、建数据库、建数据 表、插入记录、搜索记录、删除记录等基本方法。
时间: 2023-06-27 10:06:28 浏览: 123
Python操作MongoDB数据库PyMongo库使用方法
操作Mongo数据库需要先安装pymongo库,在安装前确保已经安装了MongoDB数据库。
以下是使用Python操作Mongo数据库的基本方法:
1. 连接Mongo数据库:
```python
import pymongo
#连接Mongo数据库
client = pymongo.MongoClient(host="localhost", port=27017)
```
2. 创建数据库:
```python
#创建数据库
db = client["mydatabase"]
```
3. 创建数据表(集合):
```python
#创建数据表
collection = db["customers"]
```
4. 插入记录:
```python
#插入单条记录
mydict = {"name": "John", "address": "Highway 37"}
x = collection.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 = collection.insert_many(mylist)
```
5. 搜索记录:
```python
#搜索单条记录
x = collection.find_one()
#搜索所有记录
for x in collection.find():
print(x)
#指定条件搜索
myquery = {"address": "Park Lane 38"}
mydoc = collection.find(myquery)
#模糊搜索
myquery = {"address": {"$regex": "^S"}}
mydoc = collection.find(myquery)
```
6. 删除记录:
```python
#删除单条记录
myquery = {"address": "Mountain 21"}
collection.delete_one(myquery)
#删除多条记录
myquery = {"address": {"$regex": "^S"}}
x = collection.delete_many(myquery)
#删除数据表
collection.drop()
```
以上就是使用Python操作Mongo数据库的基本方法。
阅读全文