java - 如何在 MongoDB Java 驱动程序 3 中插入​​文档

标签 java mongodb scala mongodb-java casbah

使用 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/

相关文章:

mongodb - 从其他服务器访问 MongoDB

java - Spring Mongodb 时间戳时区误导

scala - 在 Scala 中从迭代器创建 SortedMap

java - KTables如何获得它们的初始值?

java - 泛型类初始化

java - 我在 Spring Boot 中调用 API 时遇到 404 错误

scala - 如何在 play framework 2 scala 模板中创建列表

java - 操作系统中的进程和线程调度

mongodb - 错误 : while start Apache nutch with mongodb

scala - 存在类型的最佳用例