Anda harus menggunakan arrayFilter
untuk memperbarui elemen array tertentu (dengan syarat). Filter array di Java didefinisikan dengan FindOneAndUpdateOptions
objek.
List<Bson> arrFilters = new ArrayList<>();
arrFilters.add(new Document("elem.apn", "abcdef")); // this specifies the element search criteria
FindOneAndUpdateOptions updateOptions = new FindOneAndUpdateOptions().arrayFilters(arrFilters);
String [] dArray = { "app", "ban", "ora" }; // the "d" array to be added
Bson update = set("session.ps.$[elem].d", Arrays.asList(dArray));
String idStr = "5e37dc262f5ff4dfc935eb6b";
Bson queryFilter = eq("_id", new ObjectId(idStr));
Document result = coll.findOneAndUpdate(queryFilter, update, updateOptions);
System.out.println(result);
Operasi pembaruan yang sama di Mongo Shell:
var dArray = [ "app", "ban" ];
db.test.updateOne(
{ _id: ObjectId("5e37dc262f5ff4dfc935eb6b") },
{ $set: { "session.ps.$[elem].d" : dArray } },
{
arrayFilters: [ { "elem.apn": "abcdef" } ]
}
)
Memperbarui apn
bersamaan dengan nilai baru "newVal" dan menambahkan elemen string baru "gua" ke d
array (ini akan menambahkan array baru jika array tidak ada):
db.test.updateOne(
{ _id: ObjectId("5e37dc262f5ff4dfc935eb6b") },
{
$set: { "session.ps.$[elem].apn": "newVal" }
$push: { "session.ps.$[elem].d" : "gua" }
},
{
arrayFilters: [ { "elem.apn": "abcdef" } ]
}
)
Kode Java untuk kode Mongo Shell di atas:
List<Bson> arrayFilters = new ArrayList<>();
arrayFilters.add(new Document("elem.apn", "abcdef"));
FindOneAndUpdateOptions updateOptions =
new FindOneAndUpdateOptions().arrayFilters(arrayFilters);
Bson pushUpdate = push("session.ps.$[elem].d", "gua");
Bson setUpdate = set("session.ps.$[elem].apn", "newValue");
Bson update = combine(pushUpdate, setUpdate);
String idStr = "5e37dc262f5ff4dfc935eb6b";
Bson queryFilter = eq("_id", new ObjectId(idStr));
Document result = coll.findOneAndUpdate(queryFilter, update, updateOptions);