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.