Infoga dokument

Introduktion till MongoDB i Python

Filip Schouwenaars

Machine Learning Researcher

Varför infoga data?

  • Data måste finnas i din databas
  • Du behöver ett sätt att lägga till det!
  • Två metoder
    • insert_one(): lägger till ett dokument
    • insert_many(): lägger till en lista med dokument
Introduktion till MongoDB i Python

Infoga ett enskilt dokument

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

mov.count_documents({})
41
new_movie = {
    "title": "oppenheimer",
    "genre": ["drama", "history"],
    "release_year": 2023,
    "rating": 8.7
}
result = mov.insert_one(new_movie)

Ett unikt _id genereras automatiskt!

result.inserted_id
ObjectId('6837575d10d855c9f6698341')
mov.count_documents({})
42
Introduktion till MongoDB i Python

Infoga flera dokument

new_movies = [
    {
        "title": "the holdovers",
        "genre": ["comedy", "drama"],
        "release_year": 2023,
        "rating": 7.9
    },
    {
        "title": "past lives",
        "genre": ["drama", "romance"],
        "release_year": 2023,
        "rating": 7.8
    }
]
result = mov.insert_many(new_movies)
print(result.inserted_ids)
[ObjectId("662ecfe2e89c44eb19ae1234"),
 ObjectId("662ecfe2e89c44eb19ae1235")]

Alla _idn genereras automatiskt.

Introduktion till MongoDB i Python

Nu kör vi en övning!

Introduktion till MongoDB i Python

Preparing Video For Download...