所以我有一个像这样的 mongo 文档,我需要根据 val 更新数组
{
"_id" : NumberLong(222),
"pattern":"grain"
"BASIC" : {
"frame":"clear"
"tin" : [
{
"val" : "abc",
"unit" : NumberLong(2311)
},
{
"val" : "def",
"unit" : NumberLong(2311)
},
]
}
}
这是我尝试过的代码
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();
}
更新工作正常,但如果查找失败则不会更新这是我得到的错误:
com.mongodb.MongoWriteException:位置运算符未从查询中找到所需的匹配项。未扩展更新:com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:558) 处的 BASIC.tin.$.val.mongoCollectionImpl.update(MongoCollectionImpl.java:542)