如何使用其 Java 驱动程序来使用 Mongo 批量更新?
How to use Mongo Bulk Update using its Java Driver?
我正在使用 Mongo 使用其 Java 驱动程序 2.13 的批量更新。
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = (DB) mongo.getDB("test");
DBCollection collection = db.getCollection("collection");
BulkWriteOperation builder = collection.initializeOrderedBulkOperation();
builder.find(new BasicDBObject("_id", "1")).update(new BasicDBObject("_id", "1").append("name", "dev"));
我遇到以下异常:
Caused by: java.lang.IllegalArgumentException: Update document keys must start with $: _id
at com.mongodb.DBCollectionImpl$Run.executeUpdates(DBCollectionImpl.java:769)
at com.mongodb.DBCollectionImpl$Run.execute(DBCollectionImpl.java:734)
at com.mongodb.DBCollectionImpl.executeBulkWriteOperation(DBCollectionImpl.java:149)
at com.mongodb.DBCollection.executeBulkWriteOperation(DBCollection.java:1737)
at com.mongodb.DBCollection.executeBulkWriteOperation(DBCollection.java:1733)
at com.mongodb.BulkWriteOperation.execute(BulkWriteOperation.java:93)
错误的原因是因为在进行更新时您必须使用更新运算符。有关更新运算符的列表,请参阅 http://docs.mongodb.org/manual/reference/operator/update/。
从你的示例中我了解到你将名称字段设置为 "dev",因此你需要像这样使用 $set
运算符:
builder.find(new BasicDBObject("_id", "1"))
.update(new BasicDBObject("$set", new BasicDBObject("name", "dev")));
我正在使用 Mongo 使用其 Java 驱动程序 2.13 的批量更新。
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = (DB) mongo.getDB("test");
DBCollection collection = db.getCollection("collection");
BulkWriteOperation builder = collection.initializeOrderedBulkOperation();
builder.find(new BasicDBObject("_id", "1")).update(new BasicDBObject("_id", "1").append("name", "dev"));
我遇到以下异常:
Caused by: java.lang.IllegalArgumentException: Update document keys must start with $: _id
at com.mongodb.DBCollectionImpl$Run.executeUpdates(DBCollectionImpl.java:769)
at com.mongodb.DBCollectionImpl$Run.execute(DBCollectionImpl.java:734)
at com.mongodb.DBCollectionImpl.executeBulkWriteOperation(DBCollectionImpl.java:149)
at com.mongodb.DBCollection.executeBulkWriteOperation(DBCollection.java:1737)
at com.mongodb.DBCollection.executeBulkWriteOperation(DBCollection.java:1733)
at com.mongodb.BulkWriteOperation.execute(BulkWriteOperation.java:93)
错误的原因是因为在进行更新时您必须使用更新运算符。有关更新运算符的列表,请参阅 http://docs.mongodb.org/manual/reference/operator/update/。
从你的示例中我了解到你将名称字段设置为 "dev",因此你需要像这样使用 $set
运算符:
builder.find(new BasicDBObject("_id", "1"))
.update(new BasicDBObject("$set", new BasicDBObject("name", "dev")));