我已经在 MongoDB 中建模了一个具有多个关系的组,该组具有一组学生作为字段之一。
当一个学生被删除时,我想遍历所有组,并且对于在其 Group.Students 中有 deleted_student 的每个组,从数组中删除 deleted_student。
要从数组中删除 deleted_student,我有一个辅助函数 RemoveItem,我想使用它。
将此功能应用于集合中所有记录的“Mongo”方式是什么?或者我应该只返回所有组,然后遍历每个组并在字段上执行操作。像这样的东西(在 Go 中使用 mgo 库)
groups := conn.C("groups")
allGroups := groups.Find()
for _, group := range allGroups {
group.Students = RemoveItem(id, group.Students)
}
// Helper function that removes a mgo.DBRef from an array of mgo.DBRefs based on ID string
func RemoveItem(objectId string, array []mgo.DBRef) []mgo.DBRef {
updatedArray := []mgo.DBRef{}
for _, item := range array {
if item.Id != objectId {
updatedArray = append(updatedArray, item)
}
}
return updatedArray
}