Reputation: 7647
How can i write a nested query involve two collection.
For instance I have student and assignment collections.
Student:
{
"_id":"556",
"name":"sam",
"assignment":[{"2","3"}]
}
Assignment:
{
"_id":"2",
"name":"math"
}
{
"_id":"3",
"name":"english"
}
How can i write a script when student id = 556 delete, the relevant assignment documents also get delete
This is how the collection looks in json format,
{
"_id" : "123",
"media" : [
"33",
"44"
],
"sectionId" : "dd",
"courseId" : "string",
"startDate" : "string",
"endDate" : "string",
"title" : "string"
}
So i want to get the media ids and use it with a $in
Upvotes: 1
Views: 2086
Reputation: 103355
Before deleting the student, get the assignment ids in a list and then use that array as a query for removing documents in the assignment collection. Something like the following operation:
// Get assignmentIds = ["2", "3"]
var assignmentIds = db.student.findOne({"_id": "556"}).assignment;
// Delete student
db.student.remove({"_id": "556"});
// Delete associated assignments
db.assignment.remove({ "_id": { "$in": assignmentIds } });
Supposing you have a criteria that returns multiple documents and would require querying using find()
instead of findOne()
then you need to iterate the cursor returned by the find()
function, load the assignemnt id's from each document into a single array, then use that in your remove operation.
Using the same example above, you could use the forEach(
) cursor method to iterate the cursor, concatenate the assignement ids array using native JavaScript's Array.concat()
method. Consider the following example:
// Get assignment ids
var assignmentIds = [];
db.student.find({"firstName": "Jane"}).forEach(function (doc){
assignmentIds = assignmentIds.concat(doc.assignment);
});
// print the array
printjson(assignmentIds);
// Delete students
db.student.remove({"firstName": "Jane"});
// Delete associated assignments
db.assignment.remove({ "_id": { "$in": assignmentIds } });
Upvotes: 2