MongoDB Insert Document

Welcome to our detailed guide on inserting documents into MongoDB using Python. MongoDB, a popular NoSQL database, offers flexibility and scalability for handling data. Here, we’ll explore the nuances of inserting documents into a collection, managing document IDs, and efficiently handling multiple document insertions.

1. Insert Into Collection

To begin with, let’s look at how to insert a single document into a MongoDB collection.

from pymongo import MongoClient

# Connect to the MongoDB client
client = MongoClient('mongodb://localhost:27017/')

# Select the database and collection
db = client['mydatabase']
collection = db['mycollection']

# Document to be inserted
document = {"name": "John Doe", "age": 30, "address": "123 Elm Street"}

# Inserting the document
inserted_id = collection.insert_one(document).inserted_id
print(f"Document inserted with _id: {inserted_id}")

In this example, we connect to a MongoDB instance, select our database and collection, and insert a single document.

2. Return the _id Field

Every document in MongoDB has a unique _id field. When a new document is inserted, MongoDB generates an _id if it’s not provided.

# Assuming 'collection' is already defined
document = {"name": "Alice", "age": 28, "address": "456 Maple Avenue"}
inserted = collection.insert_one(document)

# Retrieving the _id of the inserted document
print(f"Inserted document ID: {inserted.inserted_id}")

3. Insert Multiple Documents

Now, let’s insert multiple documents at once using insert_many.

# List of documents
documents = [
    {"name": "Bob", "age": 25},
    {"name": "Charlie", "age": 35},
    {"name": "David", "age": 40}
]

# Inserting multiple documents
result = collection.insert_many(documents)
print(f"Documents inserted, IDs: {result.inserted_ids}")

4. Insert Multiple Documents, with Specified IDs

Sometimes, you might want to specify the _id for each document.

documents_with_ids = [
    {"_id": 1, "name": "Eve", "age": 22},
    {"_id": 2, "name": "Frank", "age": 29},
    {"_id": 3, "name": "Grace", "age": 31}
]

# Inserting documents with specified IDs
result = collection.insert_many(documents_with_ids)
print(f"Documents inserted, IDs: {result.inserted_ids}")

In this case, we are providing a custom _id for each document.

Learning MongoDB with Python is a journey of exploration and discovery. This guide is just the beginning. By mastering these basic operations, you’re well on your way to becoming proficient in handling MongoDB with Python. Remember, practice is key, so don’t hesitate to experiment with these examples and modify them to suit your learning needs.