使用casbah创建批量upsert的最佳方法

时间:2015-01-06 18:58:38

标签: casbah

我正在使用BulkWriteOperation来插入批量文档,这是我的代码

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() 

有没有办法创建Bulk Upsert?

感谢,

三木

1 个答案:

答案 0 :(得分:0)

find操作返回BulkWriteRequestBuilder,您可以replaceremoveupdate并将其标记为upsert请求。所以要执行upsert,你可以这样做:

val builder: BulkWriteOperation = collection.initializeOrderedBulkOperation
builder.find(MongoDBObject("_id" -> 1)).upsert().updateOne($set("x" -> 2))
val result = builder.execute()