Update only specific sub document deep in nested array of array of documents [duplicate]

流过昼夜 提交于 2021-02-08 10:50:49

问题


I have a sample document which has nested arrays like below. {

"locations" : [ 
        {
                "appointments" : [ 
                {
                    "apptId" : "3456",
                    "status" : ""
                }, 
                {
                    "apptId" : "12345",
                    "status" : ""
                }
            ]
        }, 
        {
            "appointments" : [ 
                {
                    "apptId" : "12345",
                    "status" : ""
                }, 
                {
                    "apptId" : "3456",
                    "status" : ""
                }
            ]
        }
]

}

I would like to update only that sub document in the nested array that that satisfies my criteria.

I have tried using the below query but I am not able to update a particular document which can be at any index in the nested array. Its giving me undesired results.

Query query = new Query();      query.addCriteria(Criteria.where("locations.appointments.apptId").is(apptId));
Update update = new Update();
update.set("locations.$[].appointments.$.status", "cancelled");

WriteResult wrote = mongoTemplate.updateMulti(query, update, Schema.class, collectionName);

My expected result is to update the status of the 2nd appointment in the first location and 1st appointment in the 2nd location(i.e. criteria matching apptId = 12345) to "cancelled". I tried using update.set("locations.$[].appointments.$.status", "cancelled"); and update.set("locations.$[].appointments.$[].status", "cancelled");, it just doesn't give me desired result.

Please help me out with this one. My MongoDB version is 3.6.10. Thanks!

来源:https://stackoverflow.com/questions/55538002/update-only-specific-sub-document-deep-in-nested-array-of-array-of-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!