Python操作MongoDB数据库基础教程
安装与连接MongoDB
在使用Python操作MongoDB之前,首先需要确保MongoDB已经安装并运行,同时还需要安装pymongo
库,它是Python与MongoDB交互的标准库。
安装pymongo库
可以使用pip
工具来安装pymongo
库。在命令行中输入以下命令:
pip install pymongo
如果使用的是Python 3.4及以上版本,也可以使用pip3
进行安装:
pip3 install pymongo
连接到MongoDB
在Python代码中,使用pymongo
库连接MongoDB非常简单。以下是一个基本的连接示例:
import pymongo
# 创建MongoClient对象,连接到本地MongoDB服务,默认端口27017
client = pymongo.MongoClient('mongodb://localhost:27017/')
# 获取一个数据库对象,如果数据库不存在,会在插入数据时自动创建
db = client['mydatabase']
在上述代码中,首先导入了pymongo
库。然后通过pymongo.MongoClient
创建了一个客户端对象,连接到本地运行的MongoDB服务。mongodb://localhost:27017/
是MongoDB的连接字符串,其中localhost
表示本地主机,27017
是MongoDB的默认端口。
接着,通过client['mydatabase']
获取了一个数据库对象。如果mydatabase
数据库不存在,在后续插入数据时会自动创建。
数据库操作
创建数据库
在MongoDB中,数据库是在插入数据时自动创建的,因此通常不需要显式创建数据库。但如果想要检查数据库是否存在,可以通过以下方式:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
# 获取所有数据库名称列表
dbs = client.list_database_names()
if'mydatabase' in dbs:
print("数据库已存在")
else:
print("数据库不存在")
上述代码通过client.list_database_names()
方法获取所有数据库名称列表,然后检查指定的数据库名称是否在列表中。
删除数据库
删除数据库也非常简单,通过client.drop_database()
方法即可实现:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
# 删除名为mydatabase的数据库
client.drop_database('mydatabase')
执行上述代码后,名为mydatabase
的数据库及其所有集合和数据将被删除。
集合操作
集合(Collection)在MongoDB中类似于关系型数据库中的表。
创建集合
与数据库类似,集合也是在插入数据时自动创建。但也可以显式创建集合,并指定一些选项,例如设置集合的最大文档数量或最大存储大小。
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
# 创建一个名为mycollection的集合
collection = db.create_collection('mycollection')
上述代码在mydatabase
数据库中创建了一个名为mycollection
的集合。如果想要设置集合的一些选项,例如设置集合的最大文档数量为1000,最大存储大小为1024000字节(1MB),可以这样做:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
# 创建一个名为mycollection的集合,设置最大文档数量为1000,最大存储大小为1MB
collection = db.create_collection('mycollection', capped=True, max=1000, size=1024000)
这里使用了capped=True
表示创建一个固定集合,固定集合有固定的大小和文档数量限制,当达到限制时,新插入的文档会覆盖最早的文档。
获取集合
获取已存在的集合非常简单,通过数据库对象直接访问集合名称即可:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
# 获取名为mycollection的集合
collection = db['mycollection']
删除集合
删除集合使用集合对象的drop()
方法:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 删除mycollection集合
collection.drop()
执行上述代码后,mycollection
集合及其所有文档将被删除。
文档操作
文档(Document)是MongoDB中的基本数据单元,类似于关系型数据库中的行记录。
插入单个文档
使用集合对象的insert_one()
方法可以插入单个文档。文档以Python字典的形式表示。
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 定义一个文档
document = {
"name": "John",
"age": 30,
"city": "New York"
}
# 插入文档
result = collection.insert_one(document)
print("插入的文档ID:", result.inserted_id)
在上述代码中,首先定义了一个文档document
,它是一个Python字典。然后通过collection.insert_one(document)
方法将文档插入到mycollection
集合中。insert_one()
方法返回一个InsertOneResult
对象,通过该对象的inserted_id
属性可以获取插入文档的唯一标识符(ObjectId)。
插入多个文档
使用集合对象的insert_many()
方法可以插入多个文档。多个文档以Python列表的形式传递,列表中的每个元素都是一个文档(字典)。
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 定义多个文档
documents = [
{
"name": "Jane",
"age": 25,
"city": "Los Angeles"
},
{
"name": "Bob",
"age": 35,
"city": "Chicago"
}
]
# 插入多个文档
result = collection.insert_many(documents)
print("插入的文档ID列表:", result.inserted_ids)
上述代码中,定义了一个包含两个文档的列表documents
,然后通过collection.insert_many(documents)
方法将这些文档插入到mycollection
集合中。insert_many()
方法返回一个InsertManyResult
对象,通过其inserted_ids
属性可以获取插入文档的唯一标识符列表。
查询单个文档
使用集合对象的find_one()
方法可以查询单个文档。find_one()
方法接受一个查询条件作为参数,该条件也是以Python字典的形式表示。如果不传递查询条件,则返回集合中的第一个文档。
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 查询name为John的文档
document = collection.find_one({"name": "John"})
print(document)
上述代码查询了mycollection
集合中name
为John
的文档,并将结果打印出来。如果查询到符合条件的文档,会返回一个字典形式的文档对象;如果没有查询到,则返回None
。
查询多个文档
使用集合对象的find()
方法可以查询多个文档。find()
方法同样接受一个查询条件作为参数,返回一个游标对象,可以通过遍历游标来获取所有符合条件的文档。
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 查询age大于30的所有文档
cursor = collection.find({"age": {"$gt": 30}})
for document in cursor:
print(document)
在上述代码中,使用{"age": {"$gt": 30}}
作为查询条件,$gt
是MongoDB的比较操作符,表示“大于”。通过遍历cursor
游标,打印出所有age
大于30的文档。
更新单个文档
使用集合对象的update_one()
方法可以更新单个文档。update_one()
方法接受两个参数,第一个参数是查询条件,用于指定要更新的文档;第二个参数是更新操作,以字典形式表示。
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 将name为John的文档的age更新为31
result = collection.update_one(
{"name": "John"},
{"$set": {"age": 31}}
)
print("匹配的文档数量:", result.matched_count)
print("修改的文档数量:", result.modified_count)
上述代码中,使用{"name": "John"}
作为查询条件,找到name
为John
的文档。使用{"$set": {"age": 31}}
作为更新操作,$set
操作符用于设置文档中指定字段的值。update_one()
方法返回一个UpdateResult
对象,通过其matched_count
属性可以获取匹配到的文档数量,modified_count
属性可以获取实际修改的文档数量。
更新多个文档
使用集合对象的update_many()
方法可以更新多个文档,其用法与update_one()
类似,只是会更新所有符合查询条件的文档。
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 将所有city为New York的文档的age增加1
result = collection.update_many(
{"city": "New York"},
{"$inc": {"age": 1}}
)
print("匹配的文档数量:", result.matched_count)
print("修改的文档数量:", result.modified_count)
这里使用{"$inc": {"age": 1}}
作为更新操作,$inc
操作符用于对指定字段的值进行增加操作。
删除单个文档
使用集合对象的delete_one()
方法可以删除单个文档。delete_one()
方法接受一个查询条件作为参数,删除第一个符合条件的文档。
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 删除name为Bob的文档
result = collection.delete_one({"name": "Bob"})
print("删除的文档数量:", result.deleted_count)
上述代码通过{"name": "Bob"}
作为查询条件,删除name
为Bob
的文档。delete_one()
方法返回一个DeleteResult
对象,通过其deleted_count
属性可以获取删除的文档数量。
删除多个文档
使用集合对象的delete_many()
方法可以删除多个文档,它接受一个查询条件作为参数,删除所有符合条件的文档。
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 删除所有city为Los Angeles的文档
result = collection.delete_many({"city": "Los Angeles"})
print("删除的文档数量:", result.deleted_count)
通过上述代码,以{"city": "Los Angeles"}
作为查询条件,删除所有city
为Los Angeles
的文档,并打印出删除的文档数量。
高级查询
条件查询操作符
除了前面提到的$gt
(大于)操作符,MongoDB还支持许多其他条件查询操作符。
$lt、$lte、$gt、$gte
这些操作符分别表示小于、小于等于、大于、大于等于。例如,查询age
大于等于25且小于等于35的文档:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
cursor = collection.find({
"age": {
"$gte": 25,
"$lte": 35
}
})
for document in cursor:
print(document)
$eq、$ne
$eq
表示等于,$ne
表示不等于。例如,查询city
不等于New York
的文档:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
cursor = collection.find({"city": {"$ne": "New York"}})
for document in cursor:
print(document)
$in、$nin
$in
用于查询字段值在指定列表中的文档,$nin
则相反,查询字段值不在指定列表中的文档。例如,查询city
为New York
或Los Angeles
的文档:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
cursor = collection.find({"city": {"$in": ["New York", "Los Angeles"]}})
for document in cursor:
print(document)
逻辑查询操作符
$and
$and
操作符用于连接多个查询条件,所有条件都必须满足。例如,查询age
大于30且city
为Chicago
的文档:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
cursor = collection.find({
"$and": [
{"age": {"$gt": 30}},
{"city": "Chicago"}
]
})
for document in cursor:
print(document)
$or
$or
操作符用于连接多个查询条件,只要有一个条件满足即可。例如,查询age
小于25或city
为New York
的文档:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
cursor = collection.find({
"$or": [
{"age": {"$lt": 25}},
{"city": "New York"}
]
})
for document in cursor:
print(document)
$not
$not
操作符用于对单个查询条件取反。例如,查询age
不大于30的文档(即age
小于等于30):
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
cursor = collection.find({"age": {"$not": {"$gt": 30}}})
for document in cursor:
print(document)
投影查询
在查询时,可以通过投影(Projection)指定返回文档中需要包含的字段,避免返回不必要的字段,从而提高查询效率。投影以字典形式表示,字段名作为键,1表示包含该字段,0表示不包含。例如,只返回name
和age
字段,不返回_id
字段(默认情况下_id
字段会返回):
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
cursor = collection.find({}, {"name": 1, "age": 1, "_id": 0})
for document in cursor:
print(document)
上述代码中,find()
方法的第一个参数为空字典,表示查询所有文档,第二个参数就是投影设置。
索引操作
索引可以显著提高查询效率,在MongoDB中同样可以为集合的字段创建索引。
创建单字段索引
使用集合对象的create_index()
方法可以创建单字段索引。例如,为mycollection
集合的name
字段创建索引:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 为name字段创建索引
index_name = collection.create_index("name")
print("创建的索引名称:", index_name)
create_index()
方法返回创建的索引名称。
创建复合索引
复合索引是基于多个字段创建的索引。例如,为mycollection
集合的name
和age
字段创建复合索引:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 为name和age字段创建复合索引
index_name = collection.create_index([("name", pymongo.ASCENDING), ("age", pymongo.DESCENDING)])
print("创建的索引名称:", index_name)
这里使用列表指定多个字段及其排序方向,pymongo.ASCENDING
表示升序,pymongo.DESCENDING
表示降序。
获取索引信息
使用集合对象的index_information()
方法可以获取集合的所有索引信息:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
index_info = collection.index_information()
print(index_info)
上述代码将打印出mycollection
集合的所有索引信息,包括索引名称和索引字段等。
删除索引
使用集合对象的drop_index()
方法可以删除指定名称的索引。例如,删除前面创建的name
字段索引:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 删除名为name_1的索引(name字段创建的索引默认名称为name_1)
collection.drop_index("name_1")
如果要删除所有索引,可以使用drop_indexes()
方法:
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mycollection']
# 删除所有索引
collection.drop_indexes()
通过以上内容,你已经对Python操作MongoDB数据库的基础有了较为全面的了解。从安装连接到数据库、集合和文档的各种操作,以及高级查询和索引操作等,这些知识足以支撑你开始使用Python与MongoDB进行数据交互开发。在实际应用中,还需要根据具体业务需求,灵活运用这些知识,优化数据库操作,提高应用程序的性能和稳定性。同时,MongoDB还有许多高级特性,如副本集、分片集群等,在处理大规模数据和高可用性场景时非常有用,后续你可以进一步深入学习。