3

If possible, I would like to return the ObjectId() generated by mongo after insertOne operation

 def insert(inputDocument : Map[String,Any], databaseName : String, collectionName : String, mongoClient : MongoClient)
  : Future[Completed] = {

    implicit val formats: DefaultFormats.type = DefaultFormats

    val createdAt = new Date()
    val createdAtUnix = System.currentTimeMillis()

    val insertJson = write( inputDocument ++ Map("createdAt" -> createdAt, "createdAtUnix" -> createdAtUnix))

    val database: MongoDatabase = mongoClient.getDatabase(databaseName)
    val collection: MongoCollection[Document] = database.getCollection(collectionName)

    val insertDocument = Document(insertJson)
    collection
      .insertOne(insertDocument)
      .toFuture()

  }

If not possible, i know it is possible to generate one, but how to be sure it's unique ?

pksimba
  • 193
  • 2
  • 10

1 Answers1

0

to get id of object which was inserted use:

collection.insertOne(e).head.map{_ => e._id.toHexString}

If you want to send your own id to mongo generate it and use immutable.Document, but with immutable document don't forget to always set _id.

to generate unique id you can use 'ObjectId.get()'

Roman Kazanovskyi
  • 3,370
  • 1
  • 21
  • 22