2016-12-13 45 views
0

所以我有这样一个蒙戈文件,我需要根据VAL更新嵌套阵列文档中的MongoDB

{ 
"_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:位置运算符没有找到所需的匹配RY。未展开的更新:。BASIC.tin $ VAL 在com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:558) 在com.mongodb.MongoCollectionImpl.update(MongoCollectionImpl.java:542)

+0

你想UPSERT到嵌入文档 “锡”? – Veeram

回答

1

的更新插入到嵌入式文件是不可能的,因此也是错误的。因此,要模拟嵌入式文档的upsert,您需要像下面那样更新您的代码。这会检查修改的计数,如果它的值为0,那么这意味着我们需要在嵌入式文档中插入一个新文档,以便使用这个文档。这将使用“pqr”作为val和“unit”作为示例文档的400。

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 
     }] 
    } 
} 
+1

谢谢,这个作品! –