0

I have a collection of student objects, I have this student document in a MongoDB collection, and want to update a teacher that belongs to one of the courses that this student has. For example I want to update the name of Danny which belongs to the Databases course.

{
    "firstName": "John",
    "lastName": "Wayne",
    "age": 25,
    "bbId": "johx0055",
    "courses" : [
        {
            "name" : "Web development",
            "teachers" : [
                {
                    "firstName" : "Bob",
                    "lastName" : "Birch"
                }
            ]
        },
        {
            "name" : "Interface Design",
            "teachers" : [
                {
                    "firstName" : "Roxanna",
                    "lastName" : "Doe"
                }
            ]
        },
        {
            "name" : "Databases",
            "teachers" : [
                {
                    "firstName" : "Jack",
                    "lastName" : "X"
                },
                {
                    "firstName" : "Danny",
                    "lastName" : "Doe"
                }
            ]
        }
    ]
}

I am trying to update this in a nodejs environment. I tried with this query and this was the closest I got to a right solution:

 db.collection('students').update({ 'bbId' : johx0055, 'courses.name' : 'Databases', 'courses.teachers.firstName' : 'Danny'}, { $set : { 'courses.$.teachers.0.firstName' : 'X' }}, (err, result) => {
    if (err) {
        console.log(err);
        //console.log({ "status": "error", "type": "001 -> create student", "message": "Error when updating teacher" });
        return;
    }
    console.log({ "status": "OK", "message": "Successfully updated teacher" });
})

But, as the 0 indicated, only updates the first element (Jack) in the teachers array

Roi
  • 983
  • 9
  • 17

1 Answers1

0

First of all, make sure to ask yourself if mongodb is the right storage solution for you. This data looks like its highly relational (Do you really want to update every student each time a course changes?)

That being said, the best way to do this I think is to overwrite the entire document with the new one you want.

var new_doc = {...}
db.save(new_doc)
Forrest Keppler
  • 577
  • 3
  • 7
  • 20
  • This is part of a assignment where we must use MongoDB, so that we can learn to query a MongoDB database. Will the db.save(new_doc) overwrite the existing object? – Roi Nov 08 '17 at 18:50
  • 1
    Every document in mongodb has an index key, when you save a new document it will look for that index key and: If it does NOT exist: save a new document If it DOES exist: update the document that has it. If I had to guess, I would guess that bbId is the indexed key in this db. But you can check using `collection.indexInformation()` – Forrest Keppler Nov 08 '17 at 18:53