作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
使用 mongodb java 驱动程序版本 3(特别是 v3.0.1)更新插入文档的惯用方法是什么?
我们有一个 session 集合,当一个新 session 被创建或修改时,我们希望在一个操作中更新它——而不是必须查询文档是否存在然后插入或替换。
我们旧的更新代码使用了 scala 驱动程序 casbah 2.7.3。它看起来像:
import com.mongodb.casbah.MongoCollection
import com.mongdb.DBObject
val sessionCollection: MongoCollection = ...
val sessionKey: String = ...
val sessionDocument: DBObject = ... // Either create a new one, or find and modify an existing one
sessionCollection.update(
"_id" -> sessionKey,
sessionDocument
upsert = true
)
在我们当前的项目中,我们只使用普通的 java 3.0.1 驱动程序,我们使用 BsonDocument
而不是 DBObject
以使其更安全。我试图用类似的东西替换上面的内容:
import com.mongodb.client.MongoCollection
val sessionCollection: MongoCollection = ...
val sessionKey: String = ...
val sessionDocument: BsonDocument = // Either create a new one, or find and modify an existing one
val updateOptions = new UpdateOptions
updateOptions.upsert(true)
sessionCollection.updateOne(
"_id" -> new BsonString(sessionKey),
sessionDocument,
updateOptions
)
这会抛出错误“java.lang.IllegalArgumentException:无效的 BSON 字段名称...”。 this question 中涵盖了该错误但是那个问题中的操作并没有试图在一个操作中插入 - 他们正在使用上下文来决定是否替换/更新/插入等...
我对 scala 或 java 中的代码示例很满意。
谢谢!
最佳答案
在 Mongo Java Driver 3.0 系列中,我们添加了一个新的 Crud API,它更加明确,因此对初学者友好。该计划已在许多 MongoDB 驱动程序中推出,但与旧 API 相比确实包含一些更改。
因为您没有使用 update operator 更新现有文档, updateOne
方法不合适。
您描述的操作是一个 replaceOne
操作,可以这样运行:
sessionCollection.replaceOne(
"_id" -> new BsonString(sessionKey),
sessionDocument,
(new UpdateOptions()).upsert(true)
)
关于java - 如何在 MongoDB Java 驱动程序 3 中插入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30611232/
我是一名优秀的程序员,十分优秀!