我有一个像这样的mongo文档结构,注释字段作为嵌入式文档。
我想添加" newField" :"" 到嵌入式注释字段" 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)
示例文档:
{
"_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帮助我。谢谢vijay
答案 0 :(得分: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);