Java + MongoDB:更新文档中的多个字段

2022-09-02 00:34:08

我正在尝试在单个MongoDB文档中一次更新多个字段,但只更新了一个字段。我有一个集合用户,其中用户由customer_user_id唯一定义。我想更新某个用户的birth_year和国家/地区字段。

这就是我正在做的:

// 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” : { “国家” : “奥地利”}}


答案 1

我无法验证,但也许你应该试试:

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));

答案 2

或者,有一些方便的方法可以做到这一点: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)
    ));

在此基础上,这也将创建一个 Bson 查询,但使用方便的方法可以使您的代码更加清晰可读。$set