Created
November 18, 2016 01:30
-
-
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.
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 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()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output: