Data model for large array of subdocuments where always fetching all, but updating individually

I have a data model with roughly this structure
document:
{
arrayOfManyItems: [{_id: …, key1: “something”}, {_id: …, key1: “somethingelse”}]
}
Where arrayOfManyItems can include large numbers of items. Getting data is always getting the entire contents of the array, but updating is only ever a single item (updating being changing the subdocument or deleting the subdocument). What’s an ideal approach to storing the data to prevent needing to change and shift every item when deleting a subdocument? If the items in the array are located using array indices it means deleting and shifting items makes async updates dangerous.

Thanks for any input!

@Dominic_Frei and @Michael_Lynn
This is a question I had in today’s webinar that was suggested to be moved here, I loved your webinar by the way!

Hi @James_Lee1 !

Welcome to the Community forum and thank you for joining the webinar. :slight_smile:

Looking at the document structure in your example I assume you won’t access the sub documents in there by array index but either by their _id or key?

If so, then deleting items, shifting them around or anything of that matter would be fine since you would pull them also by _id or key.

If we have a look at the documentation for $pull this might be what you want:

db.<YOUR_COLLECTION>.updateOne(
  { <FILTER_FOR_YOUR_MAIN_DOCUMENT> },
  { $pull:
    { arrayOfManyItems: { $key1: "something" } } 
  } 
)

<YOUR_COLLECTION> being the collection this document is in and <FILTER_FOR_YOUR_MAIN_DOCUMENT> being the filter to find the document in your example. Then you just $pull the entry with the desired key from your array.

Let me know if this is what your were looking for. :slight_smile:

Best,
Dominic

2 Likes