2014-07-04 63 views
0

我有一個mongo像這樣的文檔結構與註釋字段作爲嵌入式文檔添加新字段到mongoDB嵌入文件

我想補充「新野」: 「東西」以嵌入的註釋字段「CID」: 「17426944」

在Java驅動程序我想:

BasicDBObject query = new BasicDBObject(); // MongoDB query 
BasicDBObject record = new BasicDBObject(); // MongoDB record 
BasicDBObject dbObject = new BasicDBObject(); // fieldsToUpdate 

query.put("comments.cid","17426944"); 
dbObject.put("comments.newField","something"); 
record.put("$set",dbObject); 
mongoCtrl.updateCollection(query, record, false, true); // mongoCtrl is my connection contrl 

這裏的問題是:

com.mongodb.MongoException: cannot use the part (comments of comments.newField) to traverse the element ({comments:[ .......... ]}) 
    at com.mongodb.CommandResult.getException(CommandResult.java:100) 
    at com.mongodb.CommandResult.throwOnError(CommandResult.java:134) 
    at com.mongodb.DBTCPConnector._checkWriteError(DBTCPConnector.java:142) 

樣品DOC:

{  
     "_id" : ObjectId("53abb8d17bfd6b92e2398d34"), 
     "name" : "satish", 
     "number": "1122112", 
     "comments" : [ 
       { 
         "cid" : "17426944"       
       }, 
       { 
         "cid" : "607395840" 
       }, 
       { 
         "cid" : "393084416" 
       } 
     ] 
} 

我需要什麼:

{  
     "_id" : ObjectId("53abb8d17bfd6b92e2398d34"), 
     "name" : "satish", 
     "number": "1122112", 
     "comments" : [ 
       { 
         "cid" : "17426944", 
         "newField" : "something"  
       }, 
       { 
         "cid" : "607395840" 
       }, 
       { 
         "cid" : "393084416" 
       } 
     ] 
} 

plz幫助me.Thanks維傑

回答

1

八九不離十,你只是錯過了positional $操作相匹配的位置在您的查詢部分中找到的數組:

BasicDBObject query = new BasicDBObject(); // MongoDB query 
BasicDBObject record = new BasicDBObject(); // MongoDB record 
BasicDBObject dbObject = new BasicDBObject(); // fieldsToUpdate 

query.put("comments.cid","17426944"); 
dbObject.put("comments.$.newField","something"); 
record.put("$set",dbObject); 
mongoCtrl.updateCollection(query, record, false, true);