MongoDB のクエリオプション

Pythonで学ぶMongoDB入門

Filip Schouwenaars

Machine Learning Researcher

結果数を制限する

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

# すべての映画を取得(カーソル) all_movies = mov.find()
# 件数 len(list(all_movies))
41
from pymongo import MongoClient
client = MongoClient()
mov = client.film.movies

# 映画を5件取得(カーソル) limit_movies = mov.find().limit(5)
# 件数 len(list(limit_movies))
5
Pythonで学ぶMongoDB入門

昇順・降順でソートする

# タイトルで昇順(A-Z)
t_sort = mov.find().sort("title", 1)
list(t_sort)
[
    {
        'title': '12 angry men',
        'release_year': 1957,
        ...
    },
    {
        'title': 'a beautiful mind',
        'release_year': 2001,
        ...
    },
    ...
]
# 公開年で降順(新→旧)
ry_sort = mov.find().sort("release_year", -1)
list(ry_sort)
[
    {
          'title': 'dune: part two',
        'release_year': 2024,
        ...
    },
     {
        'title': 'barbie',
        'release_year': 2023,
          ...
    },
    ...
]
Pythonで学ぶMongoDB入門

一致ドキュメントを数える

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

# find() でアクション映画をカウント len(list(mov.find({ "genre": "action" })))
16
# より良いカウント方法
mov.count_documents({ "genre": "action" })
16
Pythonで学ぶMongoDB入門

射影で結果を整形する

movies = mov.find({}, {
  "title": 1, "rating": 1,
})
list(movies)
[
 {'_id': '6...f', 'rating': 7.6, 'title': 'superbad'},
 {'_id': '6...0', 'rating': 8.6, 'title': 'interstellar'},
 {'_id': '6...1', 'rating': 8.8, 'title': 'inception'},
 {'_id': '6...2', 'rating': 9.2, 'title': 'the godfather'},
 {'_id': '6...3', 'rating': 8,   'title': 'the revenant'},
 ...
]
movies = mov.find({}, {
  "title": 1, "rating": 1, "_id": 0
})
list(movies)
[
 {'title': 'superbad', 'rating': 7.6},
 {'title': 'interstellar', 'rating': 8.6},
 {'title': 'inception', 'rating': 8.8},
 {'title': 'the godfather', 'rating': 9.2},
 {'title': 'the revenant', 'rating': 8},
 ...
]
Pythonで学ぶMongoDB入門

練習しましょう!

Pythonで学ぶMongoDB入門

Preparing Video For Download...