0

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.

1 Answer 1

2

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))
        );
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.