Skip to content

Instantly share code, notes, and snippets.

@akiatoji
Last active November 3, 2020 09:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akiatoji/8edc3d827eaceaec5bc8b3d76422e7e6 to your computer and use it in GitHub Desktop.
Save akiatoji/8edc3d827eaceaec5bc8b3d76422e7e6 to your computer and use it in GitHub Desktop.
How to do MongoDB Group aggregation with Scala MongoDB driver
import org.mongodb.scala.bson.collection.mutable.Document
import org.mongodb.scala.{MongoClient, MongoCollection, MongoDatabase}
import org.mongodb.scala.model.Aggregates._
import org.mongodb.scala.model.Accumulators._
import com.profuzio.MongoHelper._
val mongoClient: MongoClient = MongoClient.apply("mongodb://localhost")
val database: MongoDatabase = mongoClient.getDatabase("kiwanda")
val collection: MongoCollection[Document] = database.getCollection("labor")
val v = collection.aggregate(Seq(
group(
// This is supposed to be a TExpression. Not sure what it is but this works
Document( "rvp" -> "$rvp", "rm" -> "$rm", "am" -> "$am" ),
sum("totalhours", "$TotalHours"))
)).results()
println(v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment