การคิวรีฐานข้อมูล MongoDB

MongoDB เบื้องต้นใน Python

Filip Schouwenaars

Machine Learning Researcher

ฐานข้อมูลและ collections

  • ฐานข้อมูล
    • มี collections ที่เกี่ยวข้อง
    • film
  • Collection
    • เอกสารที่มี schema แบบยืดหยุ่น
    • movies

ภาพแสดงฐานข้อมูลและ collection

MongoDB เบื้องต้นใน Python

ฐานข้อมูลและ collections ใน Python

from pymongo import MongoClient 
client = MongoClient()

# List available databases client.list_database_names()
['admin', 'config', 'film', 'local']
# List collections on film db
client.film.list_collection_names()
['movies']
MongoDB เบื้องต้นใน Python

ดึงเอกสารทั้งหมด

# Set up client
from pymongo import MongoClient 
client = MongoClient()

# Return all documents client.film.movies.find()
# Avoid dots mov = client.film.movies
mov.find()
MongoDB เบื้องต้นใน Python

จาก cursor สู่ list ใน Python

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

# Retrieve all documents
mov.find()
<pymongo.synchronous.cursor.Cursor at 0x7f...760>
list(mov.find())
[{'_id': '68...ff', 'title': 'superbad', ...
  • Cursor = ตัวชี้ไปยังผลลัพธ์ของคิวรี
  • ดึงผลลัพธ์ทีละรายการได้
  • การควบคุมนี้มีประโยชน์
MongoDB เบื้องต้นใน Python

ดูผลลัพธ์

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

# find(), cursor to list
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
    },
    ...
]
MongoDB เบื้องต้นใน Python

ตัวกรองคิวรี

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
    },
    ...
]
MongoDB เบื้องต้นใน Python

ระบุเรคคอร์ดด้วย .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 object
MongoDB เบื้องต้นใน Python

มาฝึกกันเถอะ!

MongoDB เบื้องต้นใน Python

Preparing Video For Download...