gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:54:07 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com