Update query for MongoDB in Node.js

How would you go about updating the 'status' attribute of the product "car" having a status of 0, to 1, in the purchases array of the following MongoDB Document.

MongoDB Document::

{
    "local": {
        "Name": "Rio",
        "Income": 300000,
        "purchases": [{
                "prod": "car",
                "status": 1
            },
            {
                "prod": "bike",
                "status": 0
            },
            {
                "prod": "car",
                "status": 0
            }
        ]
    }
}

3 answers

  • answered 2018-07-18 10:01 Anthony Winzlet

    You need to use $ positional operator with $elemMatch operator

    The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.

    db.collection.update(
      { "local.purchases": { "$elemMatch": { "prod": "car", "status": 0 }}},
      { "$set": { "local.purchases.$.status": 1 }}
    )
    

  • answered 2018-07-18 10:13 Siddharth Sogani

    The query will be :- db.sample.update({"local.purchases.status": 0}, {$set : {"local.purchases.$.status" : 1} });

    Explanation:- Here you will have to use $ operator to reference those purchases which are matched by the find query in the first argument fo the update function. Hope it helps.

  • answered 2018-07-18 10:40 Veeram

    You need to use $elemMatch to match the array element on both criteria.

    db.colname.update(
      {"local.purchases":{"$elemMatch":{"prod":"car", "status":0}}},
      {"$set":{"local.purchases.$.status":1}}
    )