我试图一次更新单个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);
不幸的是,仅国家/地区字段被更新,并且记录的updateQuery如下所示:
更新查询:{“ $ set”:{“ country”:“ Austria”}}
我无法验证,但也许您应该尝试:
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);
或者这与我认为的差不多:
updateQuery.put("$set", new BasicDBObject("country",country).append("birth_year", birth_year));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句