fpena06 fpena06 - 27 days ago 10
JSON Question

Positional operator to update nested array

Hello everyone I have the following document.

{
"_id" : ObjectId("568d5db6809af7688306901a"),
"name" : "name",
"market" : "market",
"state" : "state",
"products" : [
{
"updated" : ISODate("2016-11-11T23:07:11.114Z"),
"quantity" : 9,
"product" : "Prouct1",
"_id" : ObjectId("58264bd882547072b855547f")
},
{
"updated" : ISODate("2016-11-11T23:02:26.174Z"),
"quantity" : 10,
"product" : "Prouct2",
"_id" : ObjectId("58264bd882547072b855546c")
},
{
"updated" : ISODate("2016-11-11T23:02:26.174Z"),
"quantity" : 10,
"product" : "Prouct3",
"_id" : ObjectId("58264bd882547072b855548a")
},
{
"updated" : ISODate("2016-11-11T23:02:26.174Z"),
"quantity" : 10,
"product" : "Prouct4",
"_id" : ObjectId("58264bd882547072b855576a")
},
{
"updated" : ISODate("2016-11-11T22:58:14.083Z"),
"quantity" : 10,
"product" : "Prouct5",
"_id" : ObjectId("58264bd882547072b855547f")
},
{
"updated" : ISODate("2016-11-11T23:07:11.109Z"),
"quantity" : -1,
"product" : "Prouct5",
"_id" : ObjectId("58264f1fa534b62abc89edf8")
},
{
"updated" : ISODate("2016-11-11T23:07:11.119Z"),
"quantity" : -1,
"product" : "Prouct7",
"_id" : ObjectId("58264f1fa534b62abc89edfa")
}
]
}


Below is my query.

query = {'products.product': {$in: ['Prouct1', 'Prouct2', 'Prouct3']}};


But the following update only updates Prouct1. How can I change my update to update Prouct1, Prouct2 and Prouct3?

update = {$inc: {'products.$.quantity': -1},'products.$.updated': now};


As always thank you for your help and suggestions.

Answer

You cant do these using simple find query. A workaround

{$inc: {'products.0.quantity': -1,'products.1.quantity': -1,'products.2.quantity': -1}}

Or You can use a aggregation framework to $unwind your array,$match the documnet,update the documnets and again $push it into array