问题
Can someone look at this issue as we are not able to insert the array in the field 'd' as shown in the image below:
We are querying the document to update any field in the ps
array as well as insert a array in the d
field as shown below.
public void updateTesting() {
Bson where = new Document().append("_id", 123456789012345L).append("session.ps.apn","abcdef");
Bson update1=new Document().append("th", "value3");
Bson update = new Document()
.append("session.ps.$.apn", "klo");
Bson set = new Document().append("$set", update).append("$addToSet", update1);
List<Bson> list=new ArrayList<>();
list.add(set);
tim.findOneAndUpdate(where , set);
}
In the above for testing, we tried inserting an object in the 'th' field which is successful but the same was not possible for the 'd' field. Please let us know what we are doing wrong here. Please comment for any information required. Thanks in advance.
回答1:
You have to use arrayFilters to update a specific array element (with a condition). The array filters in Java is defined with FindOneAndUpdateOptions
object.
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);
The same update operation in Mongo Shell:
var dArray = [ "app", "ban" ];
db.test.updateOne(
{ _id: ObjectId("5e37dc262f5ff4dfc935eb6b") },
{ $set: { "session.ps.$[elem].d" : dArray } },
{
arrayFilters: [ { "elem.apn": "abcdef" } ]
}
)
[EDIT ADD]
Updating the apn
simultaneously with a new value "newVal" and adding a new string element "gua" to the d
array (this will add a new array if the array doesn't exist):
db.test.updateOne(
{ _id: ObjectId("5e37dc262f5ff4dfc935eb6b") },
{
$set: { "session.ps.$[elem].apn": "newVal" }
$push: { "session.ps.$[elem].d" : "gua" }
},
{
arrayFilters: [ { "elem.apn": "abcdef" } ]
}
)
The Java code for the above Mongo Shell code:
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);
来源:https://stackoverflow.com/questions/60035042/mongodb-document-update-array-element-using-findoneandupdate-method-in-java