大家好,我有一个这样的集合“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:无法使用部分(nameIdentity.sourceid的nameIdentity)来遍历元素({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也始终位于第一个文档的前面。如何更新到特定的匹配文档。
最佳答案
您错过了$
中“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
操作需要知道要处理的匹配数组元素的“索引”。否则会发生您报告的错误。