查询 MongoDB 数据库

Python 中的 MongoDB 入门

Filip Schouwenaars

Machine Learning Researcher

数据库与集合

  • 数据库
    • 相关集合
    • film
  • 集合
    • 文档,架构灵活
    • movies

visual

Python 中的 MongoDB 入门

在 Python 中的数据库与集合

from pymongo import MongoClient 
client = MongoClient()

# 列出可用数据库 client.list_database_names()
['admin', 'config', 'film', 'local']
# 列出 film 数据库的集合
client.film.list_collection_names()
['movies']
Python 中的 MongoDB 入门

获取全部文档

# 设置客户端
from pymongo import MongoClient 
client = MongoClient()

# 返回所有文档 client.film.movies.find()
# 避免重复点访问 mov = client.film.movies
mov.find()
Python 中的 MongoDB 入门

从游标到 Python 列表

# 设置客户端
from pymongo import MongoClient 
client = MongoClient()
mov = client.film.movies

# 读取所有文档
mov.find()
<pymongo.synchronous.cursor.Cursor at 0x7f...760>
list(mov.find())
[{'_id': '68...ff', 'title': 'superbad', ...
  • 游标 = 查询结果指针
  • 可逐条获取结果
  • 便于控制提取
Python 中的 MongoDB 入门

来看看输出

# 设置客户端
from pymongo import MongoClient 
client = MongoClient()
mov = client.film.movies

# find(),游标转列表
list(mov.find())
[
    {
        "_id": "6824bb...e53adbf274ff",
        "title": "superbad",
        "genre": ["comedy", "teen"],
        "release_year": 2007,
        "rating": 7.6
    },
    {
        "_id": "6824bb...e53adbf27500",
        "title": "interstellar",
        "genre": ["adventure", "drama", "sci-fi"],
        "release_year": 2014,
        "rating": 8.6,
        "won_oscar": True
    },
    ...
]
Python 中的 MongoDB 入门

查询过滤器

from pymongo import MongoClient 
client = MongoClient()
mov = client.film.movies

curs = mov.find({ "won_oscar": True }) list(curs)
[
    {
        '_id': '6824bbd05644e53adbf27500',
        'genre': ['adventure', 'drama', 'sci-fi'],
        'rating': 8.6,
        'release_year': 2014,
        'title': 'interstellar',
        'won_oscar': True
    },
     {
        '_id': '6824bbd05644e53adbf27501',
        'genre': ['action', 'sci-fi', 'thriller'],
        'rating': 8.8,
        'release_year': 2010,
        'title': 'inception',
        'won_oscar': True
    },
    ...
]
Python 中的 MongoDB 入门

用 .find_one() 精确定位

from pymongo import MongoClient 

client = MongoClient()
mov = client.film.movies

mov.find_one({ "title": "parasite" })
{
    '_id': '6824bbd05644e53adbf27518',
    'genre': ['drama', 'thriller'],
    'rating': 8.5,
    'release_year': 2019,
    'title': 'parasite',
    'won_oscar': True
}
  • 返回首个匹配文档
  • 返回文档对象,而非 Cursor
Python 中的 MongoDB 入门

¡Vamos a practicar!

Python 中的 MongoDB 入门

Preparing Video For Download...