I am currently working on developing a REST API and striving to ensure it is idempotent. One area where I am facing difficulties is with nested arrays and maintaining idempotency. I am specifically interested in updating an item within the product_notes
array in a single atomic operation. Is this achievable in MongoDB? Or should I consider storing arrays as objects instead (as demonstrated in the example at the end of this message)? Is there a way to replicate the behavior of upsert
but for arrays?
{
username: "test01",
product_notes: [
{ product_id: ObjectID("123"), note: "My comment!" },
{ product_id: ObjectID("124"), note: "My other comment" } ]
}
If I need to update the note for an existing product_node, I can simply use the update command and $set
. However, what approach should I take if the product_id
is not yet in the array? In such cases, I would like to perform an upsert
, but as far as I am aware, this functionality is not available for embedded document/array operations.
One potential solution to maintain idempotency is to create a new collection, product_notes
, to establish a relationship between product_id
and username
. Nevertheless, this approach seems to contradict the principles of document-based databases.
Alternatively:
{
username: "test01",
product_notes: {
"123": { product_id: ObjectID("123"), note: "My comment!" },
"124": { product_id: ObjectID("124"), note: "My other comment" } }
}
I would greatly appreciate insights from individuals more seasoned in this area than myself. If anyone has any advice or experiences to share on this topic, please feel free to do so.