如何在Python中使用MongoDB数据库?用法示例教程

2021年11月17日02:58:44 发表评论 739 次浏览

如何在Python中使用MongoDB?了解如何使用 pymongo 驱动程序模块在 Python 中连接到 MongoDB 数据库、列出数据库、集合、将数据插入到集合中、从集合中获取数据等,并结合相关的Python使用MongoDB示例

MongoDB是一个跨平台的面向文档的数据库。它被归类为NoSQL数据库,因为它将数据存储在灵活的、类似 JSON 的文档中,这意味着字段可以因文档而异,并且数据结构可以随着时间的推移而改变。

Python如何使用MongoDB?与将数据存储在表中的MySQL等关系数据库不同,MongoDB 以BSON格式将数据存储在集合中,这是JSON的二进制序列化,代表“二进制 JSON”,你可以用 JSON 做任何事情,你可以用 BSON 做好吧,但带有不属于 JSON 的其他扩展,例如DateBinData数据类型。

相关: 如何在 Python 中使用 JSON 文件。

选择 MongoDB 而不是 SQL 数据库的原因有很多,包括:

  • 充分利用云计算和存储
  • 灵活性
  • 加速发展
  • 它是一个分布式数据库,因此内置了高可用性、水平扩展和地理分布,并且易于使用。

这是我们将在本教程中介绍的内容:

  • 入门
  • 连接到 MongoDB 数据库
  • 列出数据库
  • 访问数据库
  • 列出数据库中的所有集合
  • 插入文件
  • 获取文件
  • 删除文档
  • 删除集合
  • 删除数据库

入门

首先,你需要在你的机器上安装 MongoDB, 我强烈建议你查看官方的 MongoDB 安装指南,你需要按照你的操作系统的步骤进行操作。

其次,你需要安装 MongoDB Python 驱动程序:pymongo

pip3 install pymongo

如何在Python中使用MongoDB?如果你只是通过pip安装pymongo,那么你就可以开始使用了,最新版本的pymongo支持所有 MongoDB 数据库版本。

最后,你需要使用以下命令启动 MongoDB 守护进程:

$ mongod

连接到 MongoDB 数据库

Python如何使用MongoDB?安装 MongoDB 并使用mongod命令启动 Mongo 守护程序后,以下代码负责连接到数据库:

from pymongo import MongoClient
from pprint import pprint

# connect to the MongoDB server
client = MongoClient()
# or explicitly
# client = MongoClient("localhost", 27017)

不传递参数与指定localhost主机和27017MongoDB的默认端口相同。请注意,这还不会建立任何连接,它只会在你执行任何操作(例如获取服务器信息)时进行。

如果你想得到一些关于服务器的信息,你可以使用client.server_info()方法。

列出数据库

Python使用MongoDB示例:让我们获取 MongoDB 服务器中可用的所有数据库:

# list all database names
print("Available databases:", client.list_database_names())

这只会输出数据库的名称,client.list_databases()如果你想获取有关数据库的一些信息(例如磁盘大小),可以使用方法,这是我的输出:

Available databases: ['admin', 'config', 'db', 'local', 'mydb']

如果你的输出与我的不同,请不要担心,我使用 MongoDB 有一段时间了,可以肯定的是,我在那里做了很多工作。

访问数据库

要访问特定的数据库,我们可以通过将其作为属性或 Python 的字典样式来访问:

# access the database "python", this will create the actual database
# if it doesn't exist
database = client["python"]
# or this:
# database = client.python

请注意,该数据库不存在,一旦我们创建一个集合(如 SQL 中的表)并插入一个文档,它就会自动创建。

使用数据库列出所有集合

Python如何使用MongoDB?集合是 MongoDB 中表的术语。要获取此数据库中的所有集合,我们只需使用database.list_collection_names()方法:

# list all collections
print("Available collections:", database.list_collection_names())

这是我的输出:

[]

并不奇怪,因为这是一个新数据库,我们还没有创建任何集合。你还可以使用database.list_collections()方法来获取每个集合以及一些信息。

插入文件

如何在Python中使用MongoDB?MongoDB 中的文档就像关系数据库中的一行。为了演示,让我们制作书籍收藏并在其中插入书籍:

# get books collection (or create one)
books = database["books"]
# insert a single book
result = books.insert_one({
    "name": "Invent Your Own Computer Games with Python, 4E",
    "author": "Al Sweigart",
    "price": 17.99,
    "url": "https://amzn.to/2zxN2W2"
})

Python使用MongoDB示例:我们已经检索了书籍集合(或者如果它不存在则创建它)并使用books.insert_one()方法插入单个文档,我们只是传递了一个 Python 字典。

让我们获取插入元素的 ID:

print("One book inserted:", result.inserted_id)

输出:

One book inserted: 5ee79b10c6bd9552e204a625

MongoDB 的一个很棒的特性,它会自动为每个插入的元素生成一个唯一的 ID,我们稍后会再次看到它。

现在如果我们想一次插入多个文档怎么办?我们简单地使用insert_many()方法而不是insert_one()

# insert many books
books_data = [
    {
        "name": "Automate the Boring Stuff with Python: Practical Programming for Total Beginners",
        "author": "Al Sweigart",
        "price": 17.76,
        "url": "https://amzn.to/2YAncdY"
    },
    {
        "name": "Python Crash Course: A Hands-On, Project-Based Introduction to Programming",
        "author": "Eric Matthes",
        "price": 22.97,
        "url": "https://amzn.to/2yQfQZl"
    },
    {
        "name": "MySQL for Python",
        "author": "Albert Lukaszewski",
        "price": 49.99,
    }
]
result = books.insert_many(books_data)
print("Many books inserted, Ids:", result.inserted_ids)

我们一次性插入了 3 个文档,注意最后一本书没有url字段,MongoDB 也没有抱怨,因为这是允许的!

这是我的输出:

Many books inserted, Ids: [ObjectId('5ee79c4fc6bd9552e204a62c'), ObjectId('5ee79c4fc6bd9552e204a62d'), ObjectId('5ee79c4fc6bd9552e204a62e')]

获取文件

Python如何使用MongoDB?MongoDB 的神奇之处在于我们可以使用 Python 字典过滤文档,让我们获取特定作者的一本书:

# get a single book by a specific author
eric_book = books.find_one({"author": "Eric Matthes"})
pprint(eric_book)

输出:

{'_id': ObjectId('5ee79c10c6bd9552e204a627'),
 'author': 'Eric Matthes',
 'name': 'Python Crash Course: A Hands-On, Project-Based Introduction to '
         'Programming',
 'price': 22.97,
 'url': 'https://amzn.to/2yQfQZl'}

输出也是一个 Python 字典,让我们获取 Al Sweigart 的所有书籍:

# get all books by a specific author
sweigart_books = books.find({"author": "Al Sweigart"})
print("Al Sweigart's books:")
pprint(list(sweigart_books))

请注意,我将结果包装在一个list()函数中以将其作为字典列表检索,这是因为find()方法返回一个pymongo.cursor.Cursor()实例,你可以在其中使用 for 循环对其进行迭代,或者使用list()函数将其包装起来。这是预期的输出:

[{'_id': ObjectId('5ee79b10c6bd9552e204a625'),
  'author': 'Al Sweigart',
  'name': 'Invent Your Own Computer Games with Python, 4E',
  'price': 17.99,
  'url': 'https://amzn.to/2zxN2W2'},
 {'_id': ObjectId('5ee79c10c6bd9552e204a626'),
  'author': 'Al Sweigart',
  'name': 'Automate the Boring Stuff with Python: Practical Programming for '
          'Total Beginners',
  'price': 17.76,
  'url': 'https://amzn.to/2YAncdY'},
 {'_id': ObjectId('5ee79c34c6bd9552e204a629'),
  'author': 'Al Sweigart',
  'name': 'Automate the Boring Stuff with Python: Practical Programming for '
          'Total Beginners',
  'price': 17.76,
  'url': 'https://amzn.to/2YAncdY'},
 {'_id': ObjectId('5ee79c4fc6bd9552e204a62c'),
  'author': 'Al Sweigart',
  'name': 'Automate the Boring Stuff with Python: Practical Programming for '
          'Total Beginners',
  'price': 17.76,
  'url': 'https://amzn.to/2YAncdY'}]

最后,如果你想在没有任何过滤器的情况下获取所有文档,你可以简单地将一个空字典传递给find()方法:

# get all documents in books collection
all_books = books.find({})
print("All books:")
pprint(list(all_books))

删除文档

如何在Python中使用MongoDB?要删除特定文档,你只需使用delete_one()方法,这是一个示例:

# delete a specific document by a JSON query
result = books.delete_one({"author": "Albert Lukaszewski"})

即使有多个文档使用该过滤器,它仍会删除单个文档。如果要使用该过滤器删除所有文档,请使用delete_many()方法:

# delete all books by Al Sweigart
result = books.delete_many({"author": "Al Sweigart"})

删除集合

Python使用MongoDB示例:要删除 MongoDB 中的集合,你有两个选择:

# drop this collection
database.drop_collection("books")
# or this:
# books.drop()

这将删除books集合。

删除数据库

# drop this entire database
client.drop_database("python")
# close the connection
client.close()

Python如何使用MongoDB?drop_database() 顾名思义,它删除给定参数中的名称的数据库。

最后,我们使用close()方法关闭连接。

结论

现在你了解了 MongoDB 及其 Python 驱动程序pymongo的基本功能。我鼓励你使用它来熟悉数据库,它和 Python 语言一样灵活!

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: