Thank you for the answer ![]()
The keys are unique and basicly the id of the item (in my case they were just examples but they are based on UUIDs in reality).
I was thinking about using an array and adding the key as an id field, but I found it hard to update the correct item later. I have multiple services that access the same database and add different values to the same “key” (sometimes even simultaneously). For example one adds/updates the “LastEvent” field and another service adds/updates a “CurrentState” field. Currently it works very easy by using an upsert and a simple set on “item.id.LastEvent” and the different services don’t interfere. If the key isn’t there yet it will just be created.
With arrays it seems to be much harder to upsert data into the array depending on a key or field inside the array.
I think I could do something similar for existing values by filtering for the item id and then using “items.$.LastEvent” to update that object, but the filter won’t work if there is no such object yet and with upsert it will just create a whole new document then.
On stackoverflow I found that question and the answers there is to use objects…but then I’m back here.
node.js - Can mongo upsert array data? - Stack Overflow
As multiple services might work on the same document I also can’t use two calls (pull and update).
![]()
I also thought about using separate documents for the items but then my problem is that I’ve a retention policy set for this collection and I then need to figure out a way to remove the other documents aswell.
As a workaround I’m now using an aggregate pipeline similar to that:
[
{$addFields:{u:{$objectToArray:"$items"}}},
{$match:{"u":{$elemMatch: { "v.LastEvent": "On" }}}},
{$project:{u:0}}
]
But I’m a bit worried about performance as I might have a huge count of documents