How to add a document to a certain MongoDB document

How to add a document to a certain MongoDB document

When you are searching on the internet how you can upload a document into a MongoDB database the most instruction uses Node.js.

But you can also use Python for this case.

The problem was in my case that I have saved a document for the tax and revenue office on an external drive, that I have scanned before. In Germany, you always get a normal letter from the tax and revenue office, yes old Germany :-(. This letter you file in a folder, and then you have to search it, if you want to see it, again.

I have made a little collection in MongoDB when a letter comes into my physical letterbox and writes the title, the date and where it comes from and the title of the letter into a collection of MongoDB. You can do it with other database system, too.

But then I have saved the scanned letter on an external drive. Normally you have not only one external drive, but a lot of. The mistake of the external drive is, that the surface is unruffled that the glue cannot hold the notice on it. Or you have another idea for this problem?

I want to say, you don’t know where you have saved this file and search in every external drive for hours.

For this case and MongoDB has this feature to save documents.

I have only explained the German old way what we get here. We don’t have here a digital online cloud from the local government, where we can see the messages from the tax and revenue office (Finanzamt), for example. Old school, Germany, regrettably.

The long and short of it, here is the code

from bson.binary import Binary
from bson.objectid import ObjectId
import pymongo

# 1. Verbindung zur lokalen MongoDB herstellen
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["Postsendungen"]  # Ersetze durch deinen Datenbanknamen
collection = db["Briefe"]

# 2. Pfad zur PDF-Datei auf der externen Festplatte
pdf_path = "/home/sk/Name_of_the_file.pdf"  # Ersetze durch den tatsächlichen Pfad

# 3. PDF im Binärmodus einlesen
with open(pdf_path, "rb") as f:
    pdf_bytes = f.read()

# 4. Gezieltes Update anhand der ObjectId
target_id = ObjectId("6909a4565eedfe5d053435f2")

result = collection.update_one(
    {"_id": target_id},
    {
        "$set": {
            "pdf_data": Binary(pdf_bytes),
            "dateiname": "Brief_vom_Finanzamt.pdf",  # optional
            "dateigroesse_bytes": len(pdf_bytes),  # optional
        }
    },
)

if result.matched_count > 0:
    print(f"PDF erfolgreich an Dokument {target_id} angehängt!")
else:
    print("Dokument mit dieser ID wurde nicht gefunden.")
Die Kommentare sind geschlossen.