Home > OS >  Mongodb Updating Nested Arrays
Mongodb Updating Nested Arrays

Time:12-03

I am trying to update the ordered quantity of the first article of the first order.

J'essaie de mettre à jour de l'attribut quantité commandé du premier article de la première commande.

Here the Screenshot of code

Here the instructions of creating and updating... voici la collection, suivie de l'instruction de mise à jour

db.client.insertOne({
    "noClient":1, "nomClient":"John Doe", "noTéléphone":"1234567890",
    "commandes":[
        {
            "noCommande":1, "dateCommande":"22-11-2022",
            "lignesCommande":[
              { "article":{"noArticle":1, "description":"Lenovo ThinkPad", "prixUnitaire":12000000, "quantiteEnStock":250}, "quantite":13 },
                { "article":{"noArticle":2, "description":"Iphone14", "prixUnitaire":16000000, "quantiteEnStock":123}, "quantite":2 },
                { "article":{"noArticle":3, "description":"All star shoes", "prixUnitaire":12500, "quantiteEnStock":15}, "quantite":1 },
                { "article":{"noArticle":4, "description":"Cahier 200pages", "prixUnitaire":12000, "quantiteEnStock":27}, "quantite":2 }
            ]
        },
        {
      "noCommande":2, "dateCommande":"23-11-2022",
            "lignesCommande":[
              { "article":{"noArticle":5, "description":"Airpods", "prixUnitaire":1300000, "quantiteEnStock":13}, "quantite":1 },
                { "article":{"noArticle":4, "description":"Cahier 200pages", "prixUnitaire":12000, "quantiteEnStock":23}, "quantite":1 }
            ]
        }
    ]
});

db.client.updateOne({"commandes.noCommande":1, "commandes.lignesCommande.article.noArticle" :1}, 
            {"$set" : {"commandes.lignesCommande.$.quantite":1}})

this command doesn't work.. plz help

db.client.updateOne({"commandes.noCommande":1, "commandes.lignesCommande.article.noArticle" :1}, {"$set" : {"commandes.lignesCommande.$.quantite":1}})

CodePudding user response:

This is actually a pain. Mongodb does not allow multiple positional operators (meaning you cannot use $ directly within your query). Instead, you could use positional filters with arrayFilters.

Playground example - https://mongoplayground.net/p/tDGYeNIYco4

db.collection.update({
  "commandes.noCommande": 1
},
{
  $set: {
    "commandes.$.lignesCommande.$[lig].quantite": 100
  }
},
{
  arrayFilters: [
    {
      "lig.article.noArticle": 1
    }
  ]
})
  • Related