Here is a code snippet,
{
"summary":[
{
"chem_id":"5e18c858c88e1e2328771593",
"chem_sale": [
{
"product_id": "5e3c5042ac7e0d67c3b5ae6f",
"product_sale": 8900
},
{
"product_id": "5e3c5029ac7e0d67c3b5ae6e",
"product_sale": 6500
}
]
},
{
"chem_id":"5e1b1cb5f3123a3a74f014f5",
"chem_sale": [
{
"product_id": "5e3c5042ac7e0d67c3b5ae6f",
"product_sale": 2900
},
{
"product_id": "5e3c5029ac7e0d67c3b5ae6e",
"product_sale": 3500
}
]
}
]
}
how to add new product object to chem_sale array if its id is unique and how to update the product_sale ?
I have tried this to add new product object to summary array
let saleRecord = await saleRecordModel.findOneAndUpdate(
{ emp_id: req.params.id },
{ $addToSet: { summary: req.body.summary } },
{ new: true, upsert: false }
);
I'm using mongoose version 5.9.0 But I'm getting duplicated results. Please help me.
What you need here is the arrayFilters
option. https://docs.mongodb.com/manual/reference/method/db.collection.update/index.html#update-array-filters
see more example for the identifier $[<identifier>]
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#up. S [%3Cidentifier%3E]
db.saleRecord.update(
{ emp_id: '<EMP_ID>' },
{ $set: {'summary.$[].chem_sale.$[chemSaleElement].product_sale': 1000 }},
{ arrayFilters: [{ 'chemSaleElement.product_id': '5e3c5029ac7e0d67c3b5ae6e' }] }
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.