我试图在单个MongoDB文档中立即更新多个字段,但只更新一个字段.我有一个集合用户,其中用户由customer_user_id唯一定义.我想更新某个用户的birth_year和country字段.
这就是我在做的事情:
// Define the search query:
DBCollection col = md.getDb().getCollection("user");
BasicDBObject searchQuery = new BasicDBObject("customer_user_id", customer_user_id);
// Define the update query:
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject().append("birth_year", birth_year);
updateQuery.append("$set", new BasicDBObject().append("country", country);
log.info("Update query: " + updateQuery);
col.update(searchQuery, updateQuery);
Run Code Online (Sandbox Code Playgroud)
不幸的是,只更新了country字段,并且记录的updateQuery如下所示:
更新查询:{"$ set":{"country":"Austria"}}
waw*_*wek 17
我无法验证,但也许你应该尝试:
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("birth_year", birth_year);
updateFields.append("country", country);
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
col.update(searchQuery, setQuery);
Run Code Online (Sandbox Code Playgroud)
或者我认为这是相同的:
updateQuery.put("$set", new BasicDBObject("country",country).append("birth_year", birth_year));
Run Code Online (Sandbox Code Playgroud)
小智 7
对于MongoDB 3.4,您可以使用
MongoCollection<Document> collection = database.getCollection(nameOfCollection);
Bson filter = new Document("SearchKey", Value);
Bson newValue = new Document("UpdateKey1", "Value1").append("UpdateKey2", "Value2")....;
Bson updateOperationDocument = new Document("$set", newValue);
collection.updateMany(filter, updateOperationDocument);
Run Code Online (Sandbox Code Playgroud)
或者,可以使用方便的方法com.mongodb.client.model.Updates
来执行此操作:
MongoCollection<Document> collection = mongoClient.getDatabase("db").getCollection("user");
collection.updateMany(
Filters.eq("customer_user_id", customer_user_id),
Updates.combine(
Updates.set("birth_year", birth_year),
Updates.set("country", country)
));
Run Code Online (Sandbox Code Playgroud)
在此基础上也会创建一个Bson查询$set
,但是使用便捷方法会使您的代码更清晰和可读。