使用Java驱动程序查找和更新(Upsert)

3

我正在尝试将代码从旧版MongoDB驱动迁移到最新版本。 在旧版中,我们有类似以下这样的代码:

BasicDBObject query = new BasicDBObject("foo", "foo");
int value = 1;
BasicDBObject field = new BasicDBObject("seq", value);
BasicDBObject update = new BasicDBObject("$inc", field);
DBObject o = getDBCollection().findAndModify(query, null, null, false, update, true, true);

如果“foo”文档不存在,则会创建它。如果存在,则seq的值将递增。
据我所知,使用MongoCollection完成相同的操作需要使用replaceOne并执行以下操作:
Document query = new Document("foo", "foo");
int value = 1;
Document field = new Document("seq", value);
Document update = new Document("$inc", field);
UpdateOptions options = new UpdateOptions().upsert(true);
UpdateResult ret = getMongoCollection().replaceOne(query, update, options);

但是这会导致java.lang.IllegalArgumentException: 无效的BSON字段名$inc。
1个回答

4
不对。您需要使用.findOneAndUpdate()方法:
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
    .upsert(true)
    .returnDocument(ReturnDocument.AFTER);

UpdateResult ret = getMongoCollection().findOneAndUpdate(query, update, options);
.replaceOne() 的意思是“替换”整个文档(除了_id)为提供的内容。这意味着像$inc这样的修饰符在此处不被允许。
因此,您需要使用.findOneAndUpdate()。请注意,您可能需要ReturnDocument.AFTER来返回“修改后”的文档,而不是更新应用之前的“原始”文档,这将是默认操作。

好的,谢谢。我之前尝试过使用findOneAndUpdate,但我没有那些选项;这就是关键所在。 - David Tong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接