Beispiel: Erstellen eines Embeddings in MongoDB

Sei folgendes Beispiel gegeben:

Wir wollen die Tabellenstruktur in folgendes Embedding überführen:

Hierzu führen wir folgende Befehle aus:

Einbetten der Employees in Department

db.Department.aggregate([
    {
        $lookup: {
            from: "Employee",
            localField: "_id",
            foreignField: "department_id",
            as: "employees"
        }
    },
    {
        $project: {
            "employees.department_id": 0
        }
    },
    {
        $merge: {
            into: "Department",
            whenMatched: "replace",
            whenNotMatched: "discard"
        }
    },
])

Einbetten des Departments in Project

db.Project.aggregate([
    {
        $lookup: {
            from: "Department",
            localField: "department_id",
            foreignField: "_id",
            as: "department"
        }
    },
    {
        $unwind: "$department" // Flatten the array into a single object
    },
    {
        $project: {
            "department_id": 0,
            "department.city": 0,
            "department.zip_code": 0,
            "department.employees": 0
        }
    },
    {
        $merge: {
            into: "Project",
            whenMatched: "replace",
            whenNotMatched: "discard"
        }
    },
])