Then I want to search in its products by Name keys,
if exists then I want to push a record document to its SalesRecord Array.
if not exists then I will add that new product document to the Products Array.
I have read that $set:{Products.Name} will satisfiy “not exist” condition but it will overwrite the existing document at “exist” condition.
The sample query I have tried is as follows but the problem with this code is $push is not allowed in the $project State.
I have managed to do the above by filtering each specific scenario and perform an update
db.collection(name).bulkWrite(
[
{ /* first scenario is Both Company and the Product exists but update newSales Object with same date`*/
updateOne:{
filter :{Company:chart[0].Company,'Products.Name' :chart[0].Products[0].Name},
update : { $set:{
"Products.$.SalesRecord.$[elem]": chart[0].Products[0].SalesRecord[0]
}
},
arrayFilters: [{"elem.Date": chart[0].Products[0].SalesRecord[0].Date }]
}
},
{ /* second scenario is Both Company and the Products exists but no Sales object with same date exists */
updateOne:{
filter: {Company:chart[i].Company,'Products.Name': chart[i].Products[0].Name,'Products.SalesRecord.Date':{$ne:chart[0].Products[0].SalesRecord[0].Date}},
update: {$push:{
"Products.$.SalesRecord": chart[i].Products[0].SalesRecord[0]
} } }
},
{
/* Third scenario is Company exists but Product not exists */
updateOne:{
filter: {Company:chart[i].Company,'Products.Name':{$ne:chart[i].Products[0].Name}},
update: {$push:{'Products': chart[i].Products[0]}}
}
},
{
/* fourth is if Company not exists */
updateOne:{
filter: {Company:chart[i].Company},
update: {$setOnInsert:{'Products': chart[i].Products}},
upsert: true
}
},
],
/* it need to be ordered for not to be conflicted*/
{ordered:true})