所以我有一个这样的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();
}
更新工作正常但如果查找失败则不会upsert 这是我得到的错误:
com.mongodb.MongoWriteException:位置运算符未找到查询所需的匹配项。未更新的更新:BASIC.tin。$。val 在com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:558) 在com.mongodb.MongoCollectionImpl.update(MongoCollectionImpl.java:542)
答案 0 :(得分:1)
嵌入文档中的upsert是不可能的,因此错误。因此,要模拟嵌入式文档的upsert,您需要更新代码,如下所示。这将检查修改后的计数,如果为0则表示我们需要在嵌入式文档中插入一个新文档,该文档使用了push。对于您拥有的示例文档,这将以“pqr”作为val并将“unit”作为400进行upsert。
Bson where = new Document().append("_id", 222).append("BASIC.tin.val","pqr");
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());
if(result.getModifiedCount() > 0){
System.out.println("updated");
} else if(result.getModifiedCount()==0){
System.out.println("upserting");
Bson where1 = new Document().append("_id", 222);
Bson upsert = new Document().append("BASIC.tin", new Document().append("val", "pqr").append("unit", 400));;
Bson push = new Document().append("$push", upsert);
UpdateResult result1 = collection.updateOne(where1 , push, new UpdateOptions());
if(result1.getModifiedCount() == 1)
System.out.println("upserted");
}else {
System.out.println("failed");
}
} catch (MongoWriteException e) {
e.printStackTrace();
}
upsert后的示例响应
{
"_id": NumberLong(222),
"pattern": "grain",
"BASIC": {
"frame": "clear",
"tin": [{
"val": "xyz",
"unit": NumberLong(2311)
}, {
"val": "def",
"unit": NumberLong(2311)
}, {
"val": "pqr",
"unit": 400
}]
}
}