gpt4 book ai didi

java - 如何在 MongoCollection Java 驱动程序 3 中执行 MongoDB findAndModify 查询?

转载 作者:IT老高 更新时间:2023-10-28 12:31:30 55 4
gpt4 key购买 nike

MongoDB 2.5 驱动程序为此提供了 DBCollection.findAndModify() 方法,但 MongoCollection 缺少此方法。经过一番搜索,我发现 findOneAndUpdate() 现在具有相同的作用。但是这个方法有不同的签名,不明白如何使用它。这是我要执行的命令

db.COL1.findAndModify({
query: { id: 2 },
update: {
$setOnInsert: { date: new Date(), reptype: 'EOD' }
},
new: true, // return new doc if one is upserted
upsert: true // insert the document if it does not exist
})

findOneAndUpdate method 的文档声明

Returns: the document that was updated. Depending on the value of the returnOriginal property, this will either be the document as it was before the update or as it is after the update.

但找不到有关此 returnOriginal 属性的任何信息。谁知道如何正确设置?

最佳答案

您的查询的 Java 等效项大致如下:

Document query = new Document("id", 2);

Document setOnInsert = new Document();
setOnInsert.put("date", new Date());
setOnInsert.put("reptype", "EOD");
Document update = new Document("$setOnInsert", setOnInsert);

FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
options.returnDocument(ReturnDocument.AFTER);
options.upsert(true);

db.getCollection("COL1").findOneAndUpdate(query, update, options);

关于 returnOriginal 属性 - 你是对的 - 没有这样的事情。 javadoc 在这个地方是无关紧要的。但是,FindOneAndUpdateOptions 中有一个 returnDocument 属性。 .您可以将其设置为 ReturnDocument.AFTERReturnDocument.BEFORE 相当于 new: true/false

关于java - 如何在 MongoCollection Java 驱动程序 3 中执行 MongoDB findAndModify 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36772054/

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