I am trying to update the ordered quantity of the first article of the first order.
Insert and update instructions:
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}})
Screenshot of code:
Following command doesn't work:
db.client.updateOne({"commandes.noCommande":1, "commandes.lignesCommande.article.noArticle" :1},
{"$set" : {"commandes.lignesCommande.$.quantite":1}})
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
}
]
})