Accessing Data with LiteDb

In my last post I talked about how easy it was to create a database with LiteDb.

But accessing your data is even easier.

To start off, assuming we have no document (i.e., structure) associated with our data – we can create a generic table on the fly using the built in BSonDocument structure.

In this example, I first use my database to get a collection of documents under “FirstTable”.  If it’s your first time creating this document, don’t worry, it’ll be created for you, so no need to do any “CREATE” mumbo jumbo.

var FirstTable = database.GetCollection("FirstTable");

Now I’m going to create some data.  The simplest, most brain-dead way to do this is to create a Dictionary, make some columns and give them whatever values I want that are of type BsonValue

Dictionary<string, BsonValue> docs = new Dictionary<string, BsonValue>();
docs.Add("living", "house");
docs.Add("address", 38);
docs.Add("pohone", "archway");

And now we insert our row into our table.

FirstTable.Insert(new BsonDocument(docs));

To see what things look like (and retrieve everything from our FirstTable), here is all you need to do.

foreach (var doc in FirstTable.FindAll()) 
Console.WriteLine("FT >>> " + doc.ToString());

If you’re looking for more information on Bson as a whole, there is a great reference here.


You can see from this quick little example that the LiteDb engine automatically creates a unique Object id field for us behind the scenes.  I would recommend creating your own Id field for tracking of your data – not only is it clean – by you can then take better advantage of the whole FindById method.  However, if you want to search by a particular value, you can use the following syntax that very easily lets you query a particular column for a piece of data.data2.PNG

Post A Reply

%d bloggers like this: