Skip to content

Instantly share code, notes, and snippets.

@tues
Created November 18, 2016 01:30
Show Gist options
  • Save tues/ec02ae8076adda7e60a58a9656d1c296 to your computer and use it in GitHub Desktop.
Save tues/ec02ae8076adda7e60a58a9656d1c296 to your computer and use it in GitHub Desktop.
A simple example showing two ways of getting IDs of documents inserted using ReactiveMongo.
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.bson.BSONObjectID
import reactivemongo.bson.BSONDocument
import scala.concurrent.Future
object Main {
def main(args: Array[String]): Unit = {
val driver = new reactivemongo.api.MongoDriver
val connection = driver.connection(List("localhost"))
val dbFuture = connection.database("mongotest")
val collectionFuture = dbFuture.map(db => db.collection("foo"))
// Using for to run futures sequentially
val queriesFuture = for {
collection <- collectionFuture
removeResult <- collection.remove(BSONDocument())
insert0Result <- collection.insert(BSONDocument("bar" -> 0))
id1 <- Future { BSONObjectID.generate() }
insert1Result <- collection.insert(BSONDocument("_id" -> id1, "bar" -> 1))
insert2Result <- collection.findAndUpdate(
selector = BSONDocument("bar" -> ""), // Make sure this won't match any document!
update = BSONDocument("bar" -> 2),
fetchNewObject = true,
upsert = true)
findResult <- collection.find(BSONDocument()).cursor[BSONDocument].collect[List]()
} yield {
println("id0: ?")
println("id1: " + id1)
insert2Result.value.map(doc => println("id2: " + doc.getAs[BSONObjectID]("_id").get))
println("All documents:")
findResult.map(doc => println(BSONDocument.pretty(doc)))
println("Done.")
}
queriesFuture.onComplete(_ => driver.close())
}
}
@tues
Copy link
Author

tues commented Nov 18, 2016

Sample output:

id0: ?
id1: BSONObjectID("582e452d0701000701808ac5")
id2: BSONObjectID("582e452dc3e2f7fa19d7413c")
All documents:
{
  _id: BSONObjectID("582e452dc3e2f7fa19d7413b"),
  bar: BSONInteger(0)
}
{
  _id: BSONObjectID("582e452d0701000701808ac5"),
  bar: BSONInteger(1)
}
{
  _id: BSONObjectID("582e452dc3e2f7fa19d7413c"),
  bar: BSONInteger(2)
}
Done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment