Nested arrays in MongoDB and useful operation

I was recently working with nested arrays embedded into a document in MongoDB – something like this, where we have the nested array named “items”



And there are situations when you need to update or remove a specified items in this array. I am going to cover the MongoDB.Driver for C# solution of this problem. Even thought this is not too complicated to achieve it took me some time to find the correct solution at Google.

The following example will update the single item in the nested array, the second item specifically, under the parent document with the specified ID:

Similar approach can be used to remove only the items in the array matching the filter. An operator/method PullFilter is used in this case and it works slightly different from the Pull method which is also available:



2 thoughts on “Nested arrays in MongoDB and useful operation”

  1. What if the items array contained a sub-array (sub-items), and you would like to update/pull from this sub-array? How would you proceed?

    1. To be honest, I do not think this would be possible with the C# MondoDB Driver. PullFilter probably cannot be used in this case. Unless there are other limitations, I would update the parent item (if the items can be tracked by ID) including the nested 2nd level array.

Send a Comment

Your email address will not be published.