So I have a mongo document like this and I need to update the array based on the val
{
"_id" : NumberLong(222),
"pattern":"grain"
"BASIC" : {
"frame":"clear"
"tin" : [
{
"val" : "abc",
"unit" : NumberLong(2311)
},
{
"val" : "def",
"unit" : NumberLong(2311)
},
]
}
}
Here is the code I've tried
collection = db.getCollection("test");
Bson where = new Document()
.append("_id", 222)
.append("BASIC.tin.val","abc");
Bson update = new Document()
.append("BASIC.tin.$.val", "xyz");
Bson set = new Document()
.append("$set", update);
try {
UpdateResult result = collection.updateOne(where, set, new UpdateOptions().upsert(true));
if (result.getMatchedCount() > 0){
System.out.println("updated");
System.out.println(result.getModifiedCount());
} else {
System.out.println("failed");
}
} catch (MongoWriteException e) {
e.printStackTrace();
}
The update works fine but does not upsert if the find fails This is the error which I get:
com.mongodb.MongoWriteException: The positional operator did not find the match needed from the query. Unexpanded update: BASIC.tin.$.val
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:558)
at com.mongodb.MongoCollectionImpl.update(MongoCollectionImpl.java:542)