MongoDB is a pretty cool document database that allows you to just toss data into a database without worrying too much about a schema.
It’s not quite that easy, of course, because your code might be looking for specific properties, but its simpler than being stuck to a rigid schema.
Lists and stuff
Recently I had a data structure where I wanted to save a list of things in each document in the database. However, I might want to update a specific item in that list, or remove a specific item in that list. Its a little more complicated than just updating a field in the document or removing the document completely, and a lot of the examples you can find online are based on JavaScript, so the fluent API that they made with the C# driver doesn’t quite work the same way.
Create
Creation is pretty easy and straightforward:
First, select the correct document out of the collection via a filter function.
Then, create an Update Builder and call the Push or PushEach functions to push new items in to the array.
Read
Reading is the same as reading any other document:
First, select the document you want with a filter function
Then, return it. Note that I’m doing a .ToList() so that the entire enumerable will be evaluated and returned.
Update
Updating is a little tricky. Since we are updating an item inside of the array Items, we need to find the right document and also find the specific MyEntityItem to update.
You can find examples of how to do this in JavaScript, but it doesn’t really help us since it isn’t exactly intuitive (at least, in my opinion) on how to map that JavaScript code to C#.
Luckily, there’s a pretty simple solution. In C# you can refer to the positional operator ($) by passing –1 (any number less than 0) as an index to your array in the Set method. Mongo will see the –1 and use the positional operator, giving us the desired effect.
First, select the document you want with a filter function
Then, Update the Item, using –1 with the square bracket operator to use the positional operator
Delete
Deletion is very similar to addition, except instead of pushing, we’re pulling.
First, select the document you want with a filter function
Then, pull the Item you want to remove with the PullFilter function