注册

Python 操作 MongoDB数据库的方法(非 ODM)

标题:Python 操作 MongoDB数据库的方法(非 ODM)完整攻略

1. 安装 pymongo 库

在 Python 中操作 MongoDB,需要使用 pymongo 库。使用 pip 命令安装:

pip install pymongo

2. 连接 MongoDB 数据库

在连接 MongoDB 数据库时,需要使用 MongoClient 类。根据 MongoDB 的地址和端口号创建 MongoClient 实例,并连接 MongoDB 数据库。

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client.test_database

以上代码中,'mongodb://localhost:27017/'是 MongoDB 的连接地址和端口号。test_database 是要使用或创建的数据库名。

3. 操作 MongoDB 数据库

具体的 MongoDB 数据库操作包括增删查改,常见的操作如下:

3.1 插入数据

使用 insert_one 或 insert_many 方法插入一条或多条数据。

collection = db.test_collection
post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python"]}
collection.insert_one(post)

3.2 查询数据

使用 find 方法查询数据。

result = collection.find_one({"author": "Mike"})

find_one 方法返回一条查询记录,使用 find 返回多个查询记录。

results = collection.find({"author": "Mike"})
for record in results:
    print(record)

3.3 更新数据

使用 update_one 或 update_many 方法更新一条或多条数据。

collection.update_one({"author": "Mike"}, {"$set": {"text": "Changed my mind about the blog post"}})

3.4 删除数据

使用 delete_one 或 delete_many 方法删除一条或多条数据。

collection.delete_one({"author": "Mike"})
collection.delete_many({"author": "Mike"})

4. 示例说明

以下两个示例说明在使用 pymongo 库操作 MongoDB 数据库时的具体使用方法。

4.1 插入数据

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client.test_database
collection = db.test_collection

post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python"]}
collection.insert_one(post)

result = collection.find_one({"author": "Mike"})
print(result)

运行结果为:

{'_id': ObjectId('5fd571cb6adef064f48450ac'), 'author': 'Mike', 'text': 'My first blog post!', 'tags': ['mongodb', 'python']}

4.2 更新数据

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client.test_database
collection = db.test_collection

collection.update_one({"author": "Mike"}, {"$set": {"text": "Changed my mind about the blog post"}})

results = collection.find({"author": "Mike"})
for record in results:
    print(record)

运行结果为:

{'_id': ObjectId('5fd571cb6adef064f48450ac'), 'author': 'Mike', 'text': 'Changed my mind about the blog post', 'tags': ['mongodb', 'python']}

以上就是 Python 操作 MongoDB 数据库的方法(非 ODM)的完整攻略,包括了 pymongo 库的安装,MongoDB 数据库的连接和增删查改等基本操作。同时,还提供了插入数据和更新数据的两个示例,方便进行更好的学习与理解。