gpt4 book ai didi

java - Mongo/Java 中 insertMany 的更新相当于什么

转载 作者:太空宇宙 更新时间:2023-11-04 13:59:55 26 4
gpt4 key购买 nike

我正在尝试进行批量更新插入,但在弄清楚如何执行此操作时遇到问题。这不起作用:

    BasicDBObject filter = new BasicDBObject();
BasicDBObject update = new BasicDBObject("$set", list);
UpdateOptions options = new UpdateOptions().upsert(true);
collection.updateMany(filter, update, options);

线程“main”com.mongodb.MongoWriteException 中出现异常:修饰符对字段进行操作,但我们发现了一个数组。

任何例子都很棒!

在一次往返中更新插入许多项目

这就是我的意思:

public static BulkWriteResult upsertAll(MongoCollection<Document> coll, List<Document> docs, String keyTag) {
List<UpdateOneModel<Document>> requests = new ArrayList<UpdateOneModel<Document>>();
UpdateOptions opt = new UpdateOptions().upsert(true);
for (Document doc : docs ) {
BasicDBObject filter = new BasicDBObject(keyTag, doc.get(keyTag));
BasicDBObject action = new BasicDBObject("$set", doc);
requests.add(new UpdateOneModel<Document>(filter, action, opt));
}
return coll.bulkWrite(requests);
}

最佳答案

您可以使用以下代码执行批量更新插入:

    MongoClient mongo = new MongoClient("localhost", 27017);
DB db = (DB) mongo.getDB("testDB");
DBCollection collection = db.getCollection("collection");

BasicDBObject obj = new BasicDBObject();
obj.append("$set", new BasicDBObject("my_field", dbList));

BasicDBList dbList = new BasicDBList();
dbList.add(1);
dbList.add(2);
dbList.add(3);

BulkWriteOperation bwo = collection.initializeUnorderedBulkOperation();
bwo.find(new BasicDBObject()).upsert().update(obj);
bwo.execute();

更多详情您可以查看:http://www.journaldev.com/6324/mongodb-upsert-example-using-mongo-shell-and-java-driver

关于java - Mongo/Java 中 insertMany 的更新相当于什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29397570/

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