我试图插入一个带有ReactiveMongo中指定的_id字段的新文档。但我的所有插入都使用Mongo默认增量objectId执行。有没有办法在插入期间指定_id?
这是我的代码。
case class MongoId($oid: String)
object MongoId {
implicit val mongoIdFormat = Json.format[MongoId]
}
case class Person(_id: MongoId, name: String)
object Person {
implicit val PersonFormat = Json.format[Person]
}
val collection = reactiveMongoApi.database.map(_.collection[JSONCollection]("people"))
def save(person: Person) = {
collection.flatMap(d => d.insert(person)).map(wr => wr.hasErrors match {
case true => None
case false => Some(person)
})
}
答案 0 :(得分:0)
当然有办法。在插入MongoDB之前,您需要自己生成ObjectId
。示例如下。
case class Person (_id: BSONObjectID, name: String)
object Person {
implicit val PersonFormat = Json.format[Person]
}
val p = Person(BSONObjectID.generate, "Mac")
save(p)