0

im using BulkWriteOperation in order to insert bulk Documents ,this is my code

val builder: casbah.BulkWriteOperation = collection.initializeOrderedBulkOperation

for(p<-posts){

 if (p._1.\("object_id").asOpt[String].getOrElse("") != "" && p._1.\("message").asOpt[String].getOrElse("") !="")
 builder.insert(MongoDBObject("id" -> p._1.\("id").asOpt[String], "object_id" -> p._1.\("object_id").asOpt[String], "message" -> p._1.\("message").asOpt[String],"shares"->p._1.\("shares").\("count").asOpt[Long].getOrElse(0),"likes"->p._2.\("summary").\("total_count").asOpt[Long].getOrElse(0)))

}

val result = builder.execute() 

Is there any way to create Bulk Upsert ?

thanks,

miki

MIkCode
  • 2,655
  • 5
  • 28
  • 46

1 Answers1

0

Yes the find operation returns a BulkWriteRequestBuilder which allows you to replace, remove, update and mark it as an upsert request. So to perform an upsert you can do:

val builder: BulkWriteOperation = collection.initializeOrderedBulkOperation
builder.find(MongoDBObject("_id" -> 1)).upsert().updateOne($set("x" -> 2))
val result = builder.execute() 
Ross
  • 17,861
  • 2
  • 55
  • 73