單層數(shù)組嵌套示例:
{
"_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;
// 構(gòu)建匹配文檔的查詢條件
Bson match = Filters.eq("_id", "someId");
// 構(gòu)建更新操作,目標(biāo)是修改嵌套數(shù)組中特定對(duì)象的字段
Bson updateOperation = Updates.set("arrayField.$[elem].updateKey", "newValue");
// 指定數(shù)組過濾條件,用于匹配需要更新的數(shù)組元素
UpdateOptions options = new UpdateOptions().arrayFilters(Arrays.asList(Filters.eq("elem.fieldKey", "targetValue")));
// 執(zhí)行更新操作
collection.updateOne(match, updateOperation, options);
兩層數(shù)組嵌套示例:
{
"_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");
// 構(gòu)建查詢條件,匹配f2等于k4的文檔
Document matchCondition = new Document("arrayField.updateKey.f2", "k4");
// 構(gòu)建更新操作,這里需要使用$操作符來精確指定路徑
Document updateOperation = new Document("$set", new Document("arrayField.$.updateKey.$[elem].f2", "new_value"));
// 構(gòu)建數(shù)組過濾器,以便只更新匹配的子文檔
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();
}
}
}