New to mongodb, Tring to update multiple array object field of an document. not getting expected result
Document Structure:
{
"_id" : ObjectId("4faaba123412d654fe83hg876"),
"user_id" : 123456,
"items" : [{
Name:{
"id":1,
"item_name" : "my_item_one",
"price" : 20
},
Details:{
"Date" : "10/02/2022",
"Address":"test"
}}],
[{
Name:{
"id":2,
"item_name" : "my_item_two",
"price" : 20
},
Details:{
"Date" : "10/02/2022",
"Address":"test"
}}]
}
Based on id need to update date
Spring boot code
Query query = new Query(Criteria.where("user_id").is("123456").and("items")
.eleMatch(Criteria.where("items.Name.id").is(1)));
Update update = new Update().set("items.0.Details.Date", "29/01/2022");
mongoOperation.findAndModify(query, update, Items.class);
but when I run this query it is returning null Can any one help on this Thanks , Also tried
Query query = new Query(Criteria.where("user_id").is("123456").and("items")
.eleMatch(Criteria.where("items.Name.id").is(1)));
Update update = new Update().set("items.Details.Date", "29/01/2022");
mongoOperation.findAndModify(query, update, Items.class);
CodePudding user response:
i think your query doesn't find anything to update. try running the query as a "find" in java and see which document comes back. my hunch is that the "and eleMatch" part is wrong. just query for the entire document by the user_id, and execute the update on the specific field. also, the syntax on the update you described will update all items, you need to specify the index in the array. perhaps doing the update manually in java would be easier.