MongoDB में क्वेरी विकल्प

Python में MongoDB परिचय

Filip Schouwenaars

Machine Learning Researcher

परिणामों की संख्या सीमित करना

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

# सभी फिल्में प्राप्त करें (cursor) all_movies = mov.find()
# कितनी? len(list(all_movies))
41
from pymongo import MongoClient
client = MongoClient()
mov = client.film.movies

# पाँच फिल्में प्राप्त करें (cursor) 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 परिचय

Projection से अपने परिणाम आकार दें

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...