In the previous post we created a document called Quiz and inserted Questions into it. Each item in the Questions collection has a question, choices and answer. In this post let’s play with the CRUD operations. You can switch to Quiz document with “use Quiz” command.
- You can retrieve questions using find() method. The find() method accepts two JSON objects as arguments. The first one is the criteria and the second is the filter. Let’s select the question and choices of all the questions whose answer is 5.
db.Questions.find({answer:”5″},{question:1,choices:1,_id:0})
The 1 and 0 in the second argument specify whether the field has to be retrieved or not. You will get an output as like this. - Say you want to find the questions with answer as 2 and add “None of the above” option to the choices of questions. You can use the update() method for this purpose.
db.Quiz.update({answer:”2″},{$push:{choices:”None of the above”}},{multi:true});
The code above can be read as get all the items with answer as 2 and push “None of the above” to the choices property.
- If you want to delete a record you can use the remove() method.
db.Questions.remove({answer:”5″});
So, here we remove the records that have 5 as the answer.
In the next post, let’s play with some more operations on the Questions data.