Inserire documenti

Introduzione a MongoDB in Python

Filip Schouwenaars

Machine Learning Researcher

Perché inserire dati?

  • I dati devono esistere nel tuo database
  • Serve un modo per aggiungerli!
  • Due metodi
    • insert_one(): aggiunge un singolo documento
    • insert_many(): aggiunge un elenco di documenti
Introduzione a MongoDB in Python

Inserire un singolo documento

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)

L'_id univoco viene generato automaticamente!

result.inserted_id
ObjectId('6837575d10d855c9f6698341')
mov.count_documents({})
42
Introduzione a MongoDB in Python

Inserire più documenti

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")]

Tutti gli _id sono generati in automatico.

Introduzione a MongoDB in Python

Esercitiamoci!

Introduzione a MongoDB in Python

Preparing Video For Download...