1

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:

[![JSON Structure in MongoDB][1]][1]

{
  "id": 12,
  "articles": "art",
  "author": "author"
}

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

9 Comments

(1) The eq and set static methods are from com.mongodb.client.model.Filters and com.mongodb.client.model.Updates classes.
Thank you but the issue is we need to update the apn field simultaneously which is not happening.
Please explain "... we need to update the apn field simultaneously".
I added the Mongo Shell code. Please check if it is what you wanted - the same update query additionally updates the apn field with a newly supplied value.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.