1

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.

Community
  • 1
  • 1
fpena06
  • 2,246
  • 3
  • 20
  • 28

1 Answers1

2

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

Parshuram Kalvikatte
  • 1,616
  • 4
  • 20
  • 40