MongoDB : given an array of objects, update the ones that are existing or add if it is not existing
I have an array of objects that looks like this:
[
{
customer_id: "A100",
status: "purchased",
order_price: 30,
},
{
customer_id: "A102",
status: "in cart",
order_price: 50,
},
{
customer_id: "A103",
status: "in cart",
order_price: 60,
},
{
customer_id: "A102",
status: "purchased",
order_price: 70,
}
]
I want to update the documents in my database based on the customer_id
, such that if any document with customer_id
of A100 or A102 etc
is existing it should update it, and if not it should add it.
Assume my database has the following documents:
[
{
customer_id: "A100",
status: "in cart",
order_price: 30,
},
{
customer_id: "A102",
status: "viewing",
order_price: 20,
},
{
customer_id: "B100",
status: "purchased",
order_price: 100
}
]
after the operation, my database should look like this
[
{
customer_id: "A100",
status: "purchased",
order_price: 30,
},
{
customer_id: "A102",
status: "in cart",
order_price: 50,
},
{
customer_id: "A103",
status: "in cart",
order_price: 60,
},
{
customer_id: "A102",
status: "purchased",
order_price: 70,
},
{
customer_id: "B100",
status: "purchased",
order_price: 100
}
]
NOTE : the document with customer_id: "B100"
is still left untouched