使用MongoDB Java 3.0驱动程序批量Upsert

编程入门 行业动态 更新时间:2024-10-27 04:31:05
本文介绍了使用MongoDB Java 3.0驱动程序批量Upsert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在MongoDB Java驱动程序的早期版本中,要运行查询并对结果执行无序批量upsert,我们所做的就是:

In the earlier versions of MongoDB Java drivers , to run a query and do unordered bulk upsert on the result all we had do was :

BulkWriteOperation bulk = dbCollection.initializeUnorderedBulkOperation(); bulk.find(searchQuery).upsert().update(new BasicDBObject("$set", getDbObjectModel()));

但是在版本3中,随着Bson Document支持和MongoCollection.bulkWrite()方法的引入怎么能这样做了吗?

But in version 3, with the introduction of Bson Document support and MongoCollection.bulkWrite() method how can this be done?

我试过这个:

List<WriteModel<Document>> documentList = new ArrayList<>(); collection.bulkWrite(documentList, new BulkWriteOptions().ordered(false));

但是,我需要upsert功能。

but, I need the upsert functionality.

谢谢。

推荐答案

您仍然可以使用所有功能,只是BulkWrites现在有不同的语法:

You can still use all of the functionality, it's just that BulkWrites now have a different syntax:

MongoCollection<Document> collection = db.getCollection("sample"); List<WriteModel<Document>> updates = Arrays.<WriteModel<Document>>asList( new UpdateOneModel<Document>( new Document(), // find part new Document("$set",1), // update part new UpdateOptions().upsert(true) // options like upsert ) ); BulkWriteResult bulkWriteResult = collection.bulkWrite(updates);

所以你使用 UpdateOneModel (如果需要,可以为很多人设置)并设置 UpdateOptions 作为构造函数的第三个参数。

So you use the UpdateOneModel ( or for many if you want ) and set the UpdateOptions as the third argument to the constructor.

需要习惯,但它基本上只是构建列表,其语法与其他地方相同。我猜这是改变的主要原因。

Takes some getting used to, but it's basically just building "Lists" with all the same syntax as elsewhere. I guess that's the main reason for the change.

更多推荐

使用MongoDB Java 3.0驱动程序批量Upsert

本文发布于:2023-11-22 12:55:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617498.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:批量   驱动程序   Java   MongoDB   Upsert

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!