Iva
Iva

Reputation: 101

Updating an embedded document in MongoDB using Java

I'm new to Mongo and I'm trying to add a new field to an array of objects in Mongo. I have a collection of Students that has student objects inside. Here is what my document looks like:

Student{
       "id":"...",
       "Name":"...",
       "username":"...",

       "courses":[
               {
                  "course name":"English",
                  "course id":"ENC1101",                                    
               },
               {
                  "course name":"Math",
                  "course id":"MA1453",                                   
               },
               {
                  "course name":"Biology",
                  "course id":"BA1403",                                    
               }


     ]
}

So what I would like to do is add a new field to every course(for every student in the students collection) which will be called module and this is what I tried:

DBCursor cursor = students.find();
while(cursor.hasNext()) {
     BasicDBObject modules = new BasicDBObject("modules", "moduleID");

     BasicDBObject courses = new BasicDBObject("courses", modules); 

     BasicDBObject withSet = new BasicDBObject("$push", courses);

     students.update(cursor.next(), withSet);
}

However this adds a new element to the array of courses, not to every course. I do not know how to loop through this array add a filed to every object in this array so any help would be appreciated.

Upvotes: 0

Views: 1178

Answers (1)

user508434
user508434

Reputation:

The $push operator appends a new element into the array. That is why your collections gets added a new element. One solution is to replace the whole array with the $set operator. You iterate over the students and for each students' course you append the moduleId to the course element:

    DBCursor cursor = students.find();
    while (cursor.hasNext()) {
        final DBObject student = cursor.next();
        BasicDBList courses = (BasicDBList) student.get("courses");
        for (Object course : courses) {
            ((BasicDBObject) course).append("modules", "moduleID");
        }
        students.update(
                        new BasicDBObject("id","test"), //update query
                        new BasicDBObject("$set", new BasicDBObject("courses", courses))
        );
    }

Upvotes: 2

Related Questions