{"id":4053,"date":"2016-06-18T20:15:32","date_gmt":"2016-06-18T20:15:32","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=4053"},"modified":"2016-06-18T20:15:32","modified_gmt":"2016-06-18T20:15:32","slug":"embedded-nosql-with-litedb","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/embedded-nosql-with-litedb\/","title":{"rendered":"Embedded NoSQL with LiteDB"},"content":{"rendered":"<p>I was looking for a simple file based object\/document database and came across <a href=\"http:\/\/www.litedb.org\/\" target=\"_blank\">LiteDB<\/a>. This gives similar functionality to MongoDB.<\/p>\n<p>If you&#8217;re looking for good documentation on LiteDB, I would suggest going to <a href=\"https:\/\/github.com\/mbdavid\/LiteDB\/wiki\/Getting-Started\" target=\"_blank\">Getting Started<\/a>. I&#8217;ll undoubtedly duplicate some\/much of what&#8217;s written there in this post which is mainly aimed at reminding me how to get up and running with LiteDB.<\/p>\n<p><strong>Getting started<\/strong><\/p>\n<p>It&#8217;s so easy to get started with LiteDB. Let&#8217;s first define an object model for some data that we might wish to store.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class Artist\r\n{\r\n   public string Name { get; set; }\r\n   public IList&lt;string&gt; Members { get; set; }\r\n}\r\n\r\npublic class Album\r\n{\r\n   public int Id { get; set; }\r\n   public Artist Artist { get; set; }\r\n   public string Name { get; set; }\r\n   public string Genre { get; set; }\r\n}\r\n<\/pre>\n<p><em>We need an Id property or a property marked with a BsonId attribute on our POCO object. Whilst we can get away without this for some operations, updates (for one will fail) without the Id property\/BsonId.<\/em><\/p>\n<p>To use LiteDB, simply install the nuget package <em>LiteDB<\/em> and now here&#8217;s the bare minimum to create\/open a LiteDB database file and get a reference to the collection for our CRUD operations<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing (var db = new LiteDatabase(&quot;Albums.db&quot;))\r\n{\r\n   var albums = db.GetCollection&lt;Album&gt;(&quot;albums&quot;);\r\n   \/\/ now we can carry out CRUD operations on the data\r\n}\r\n<\/pre>\n<p>Easy enough. The <em>LiteCollection<\/em> returned from <em>GetCollection<\/em> allows us to to work on our data in a very simple manner. <\/p>\n<p>For example, let&#8217;s insert a new album<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nalbums.Insert(\r\n   new Album\r\n   {\r\n      Artist = new Artist\r\n      {\r\n         Name = &quot;Led Zeppelin&quot;,\r\n         Members = new List&lt;string&gt;\r\n         {\r\n            &quot;Jimmy&quot;, &quot;Robert&quot;, &quot;JP&quot;, &quot;John&quot;\r\n         }\r\n      },\r\n      Name = &quot;Physical Graffiti&quot;,\r\n      Genre = &quot;Rock&quot;\r\n   });\r\n<\/pre>\n<p>How about retrieving all the data, we can use<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nvar results = albums.FindAll();\r\n<\/pre>\n<p>We can also query for specific data using a predicate, for example<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nvar r = albums.Find(a =&gt; a.Artist.Name == &quot;Alice Cooper&quot;);\r\n<\/pre>\n<p><em>Note: in this example, the Artist.Name property has not been indexed, so performance would be improved by setting an index on the data.<\/em><\/p>\n<p>To update we need to get the instance from LiteDB (or at least know the Id) and then makes the changes as follows<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nvar zep = albums.Find(a =&gt; a.Artist.Name == &quot;Led Zeppelin&quot;).First();\r\nzep.Artist.Members&#x5B;2] = &quot;John Paul Jones&quot;;\r\nalbums.Update(zep);\r\n<\/pre>\n<p>Obviously in the above we&#8217;re assuming there&#8217;s at least one item (by calling First() as obviously there might be zero, one or multiple returns), the key is how we simply call the Update method.<\/p>\n<p>Deleting all items from a database can be achieved, obviously by deleting the DB file or using<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nalbums.Delete(Query.All());\r\n<\/pre>\n<p>or we can delete an individual item by calling<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n\/\/ use the Id property \r\nalbums.Delete(album.Id); \r\n\r\n\/\/ or\r\n\r\n\/\/ use a query type syntax\r\nalbums.Delete(x =&gt; x.Artist.Name == &quot;Led Zeppelin&quot;); \r\n\r\n\/\/ or\r\n\r\n\/\/ using the Query syntax similar to deleting all items\r\nalbums.Delete(Query.EQ(&quot;Artist.Name&quot;, new BsonValue(&quot;Led Zeppelin&quot;)));\r\n<\/pre>\n<p>Obviously the Query syntax seems a little over the top for most things, but offers more query like syntax if required.<\/p>\n<p><strong>And there&#8217;s more<\/strong><\/p>\n<p>Okay I&#8217;m not intending to document everything in this single post but I have to just touch on transactions. It&#8217;s great to see the ability to use ACID transactions for use with LiteDB.<\/p>\n<p>So to ensure we only commit when all operations are successful we simply use<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nvar albums = db.GetCollection&lt;Album&gt;(&quot;albums&quot;);\r\n\r\ndb.BeginTrans();\r\n\/\/ multiple operations against LiteDB\r\ndb.Commit();\r\n<\/pre>\n<p><strong>Multiple Inserts<\/strong><\/p>\n<p>It seems (from the documentation etc.) that when we carry out an insert, LiteDB creates an &#8220;auto-transaction&#8221; around the insert for us (see <a href=\"https:\/\/github.com\/mbdavid\/LiteDB\/wiki\/Transactions-and-Concurrency\" target=\"_blank\">Transactions and Concurrency<\/a>. As such we should be aware that if we&#8217;re creating many inserts (for example from a list of objects) then it&#8217;s best from a performance point of view to not call insert multiple times.<\/p>\n<p>Instead either using the IEnumerable overload of the Insert method or wrap all inserts within a transaction (I&#8217;m assuming this would also work &#8211; not yet tested).<\/p>\n<p>This make sense, but can be easily forgotten.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I was looking for a simple file based object\/document database and came across LiteDB. This gives similar functionality to MongoDB. If you&#8217;re looking for good documentation on LiteDB, I would suggest going to Getting Started. I&#8217;ll undoubtedly duplicate some\/much of what&#8217;s written there in this post which is mainly aimed at reminding me how to [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[123],"tags":[],"class_list":["post-4053","post","type-post","status-publish","format-standard","hentry","category-litedb"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/4053","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=4053"}],"version-history":[{"count":13,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/4053\/revisions"}],"predecessor-version":[{"id":4077,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/4053\/revisions\/4077"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=4053"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=4053"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=4053"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}