你好,我有一个像这样的集合“”_id“:ObjectId(”55dabba974cd60712be24443“),
"entityType" : "1",
"entityCreatedDate" : "08/24/2015 12:07:20 PM",
"nameIdentity" : [
{
"givenNameOne" : "JOY",
"givenNameThree" : "BRAKEL",
"lastName" : "BRAKEL",
"createdDate" : "08/24/2015 12:07:20 PM",
"sourceId" : [
{
"sourceId" : "55dabba974cd60712be24441"
}
]
},
],
Here name identity is a list as well as sourceId. I am trying to update sourceId list in nameIdentityList if it matches the names. My java code is :
Document sourceDocument=new Document("sourceId",sourceId);
mongoDatabase.getCollection("entity").updateOne(new Document("entityId", entityId).append("nameIdentity.givenNameOne","JOY"),
new Document("$push", new Document("nameIdentity.sourceId", sourceDocument)));
`但是我得到的异常就像java.lang.RuntimeException:com.mongodb.MongoWriteException:不能使用part(nameIdentity of nameIdentity.sourceId)来遍历元素({nameIdentity。
如果我的情况满意,我期待这样:
`"_id" : ObjectId("55dabba974cd60712be24443"),
"entityType" : "1",
"entityCreatedDate" : "08/24/2015 12:07:20 PM",
"nameIdentity" : [
{
"givenNameOne" : "JOY",
"givenNameThree" : "BRAKEL",
"lastName" : "BRAKEL",
"createdDate" : "08/24/2015 12:07:20 PM",
"sourceId" : [
{
"sourceId" : "55dabba974cd60712be24441"
},
{
"sourceId" : "55dabba974cd60712be24435"
}
]
},
],`
。我有什么错误吗? 我的nameIdentity中有多个名称,即使匹配的文档是第二个或第三个,sourceId也始终被添加到第一个文档中。如何更新到特定的匹配文档。
答案 0 :(得分:1)
在" nameIdentity"之后,您错过了positional $
运营商$push
中的字段:
Document sourceDocument=new Document("sourceId",sourceId);
mongoDatabase.getCollection("entity").updateOne(
new Document("entityId", entityId).append("nameIdentity.givenNameOne","JOY"),
new Document("$push", new Document("nameIdentity.$.sourceId", sourceDocument))
);
与其他更新操作修饰符一样的$push
操作需要知道"索引"要处理的匹配数组元素。否则会报告您报告的错误。