Last active
December 14, 2015 17:59
-
-
Save ojacquemart/5125642 to your computer and use it in GitHub Desktop.
Mongo M101J : Week2#Exercise2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import play.api._ | |
import play.api.libs.json._ | |
import play.api.mvc._ | |
import play.api.Logger | |
import play.api.Play.current | |
import play.modules.reactivemongo._ | |
import play.modules.reactivemongo.ReactiveMongoPlugin | |
import org.joda.time.DateTime | |
import reactivemongo.bson._ | |
import reactivemongo.bson.handlers.DefaultBSONHandlers.DefaultBSONDocumentWriter | |
import reactivemongo.bson.handlers.DefaultBSONHandlers.DefaultBSONReaderHandler | |
import reactivemongo.bson._ | |
import reactivemongo.bson.handlers._ | |
import scala.concurrent.{ExecutionContext, Future} | |
import ExecutionContext.Implicits.global | |
case class Grade(id: Option[BSONObjectID], typeHomework: String, studentId: Int, score: Double) | |
object GradeBSON { | |
implicit object GradeBSONReader extends BSONReader[Grade] { | |
def fromBSON(document: BSONDocument): Grade = { | |
val doc = document.toTraversable | |
val page = Grade( | |
doc.getAs[BSONObjectID]("_id"), | |
doc.getAs[BSONString]("type").get.value, | |
doc.getAs[BSONInteger]("student_id").get.value, | |
doc.getAs[BSONDouble]("score").get.value) | |
page | |
} | |
} | |
} | |
object MongoCourse extends Controller with MongoController { | |
def db = ReactiveMongoPlugin.db | |
def collection = db("grades") | |
def findAnswer = Action { | |
Async { | |
implicit val reader = GradeBSON.GradeBSONReader | |
val selector = BSONDocument( | |
"$orderby" -> BSONDocument( | |
"student_id" -> BSONInteger(1), "score" -> BSONInteger(1) | |
), | |
"$query" -> BSONDocument( | |
"type" -> BSONString("homework") | |
) | |
) | |
val query = collection.find(selector) | |
query.toList().map { | |
grades => { | |
println("grades " + grades.size) | |
deleteStudentsLowerScore(grades) | |
Ok | |
} | |
} | |
} | |
} | |
def deleteStudentsLowerScore(grades: List[Grade]) { | |
val groups = grades.groupBy(_.studentId) | |
val ids = groups.map(g => g._2.head.id.get) | |
ids.foreach(id => { | |
val query = BSONDocument("_id" -> id) | |
collection.remove(query) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment