单层数组嵌套示例:
{
"_id": "someId",
"arrayField": [
{
"fieldKey": "targetValue",
"updateKey": "oldValue"
},
{
"fieldKey": "otherValue",
"updateKey": "value"
}
]
}
代码:
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import org.bson.Document;
import org.bson.conversions.Bson;
// 构建匹配文档的查询条件
Bson match = Filters.eq("_id", "someId");
// 构建更新操作,目标是修改嵌套数组中特定对象的字段
Bson updateOperation = Updates.set("arrayField.$[elem].updateKey", "newValue");
// 指定数组过滤条件,用于匹配需要更新的数组元素
UpdateOptions options = new UpdateOptions().arrayFilters(Arrays.asList(Filters.eq("elem.fieldKey", "targetValue")));
// 执行更新操作
collection.updateOne(match, updateOperation, options);
两层数组嵌套示例:
{
"_id": "someId",
"arrayField": [
{
"fieldKey": "targetValue",
"updateKey": [
{
"f1":"k1",
"f2":"k2"
},
{
"f1":"k3",
"f2":"k4"
}
]
},
{
"fieldKey": "otherValue",
"updateKey": [
{
"f1":"k1",
"f2":"k2"
},
{
"f1":"k3",
"f2":"k4"
}
]
}
]
}
代码如下:
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Updates.set;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.UpdateResult;
public class MongoDBUpdateExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
MongoDatabase database = mongoClient.getDatabase("yourDatabaseName");
MongoCollection<Document> collection = database.getCollection("yourCollectionName");
// 构建查询条件,匹配f2等于k4的文档
Document matchCondition = new Document("arrayField.updateKey.f2", "k4");
// 构建更新操作,这里需要使用$操作符来精确指定路径
Document updateOperation = new Document("$set", new Document("arrayField.$.updateKey.$[elem].f2", "new_value"));
// 构建数组过滤器,以便只更新匹配的子文档
UpdateOptions options = new UpdateOptions().arrayFilters(
java.util.Arrays.asList(new Document("elem.f2", "k4"))
);
UpdateResult result = collection.updateMany(matchCondition, updateOperation, options);
System.out.println("Matched count: " + result.getMatchedCount());
System.out.println("Modified count: " + result.getModifiedCount());
} catch (Exception e) {
e.printStackTrace();
}
}
}