Language: EN

litedb

LiteDB, embedded NoSQL database for .NET

LiteDB is a lightweight, open-source embedded NoSQL database, available in C# for use in our .NET applications.

It is an interesting option to add to a project when we need to store relatively small amounts of data, but do not want to use a “big” database like SQL Server or MongoDB, nor work with JSON files.

LiteDB is a document-oriented embedded NoSQL database, which is simple and easy to use. Its API has been designed to be similar to MongoDB, and it is compatible with LINQ.

In general, LiteDB is suitable for small and medium-sized applications, without user concurrency requirements. For example, when you create a console application that only you will use, and you need to store data quickly and easily.

It is entirely developed in C#, with no external dependencies. It has been optimized to be very lightweight, the entire file occupies less than 450Kb.

On the other hand, in the same project, a small tool is provided, LiteDB Studio, to manage the data stored in the database.

It is compatible with .NET Framework 4.5 or higher, and .NET Standard 1.3 and 2.0.

How to use LiteDB

We can easily add the library to a .NET project through the corresponding Nuget package.

Install-Package LiteDB

Now we can use LiteDB in our project. For example, suppose we have a Customer class that looks like this

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string[] Phones { get; set; }
    public bool IsActive { get; set; }
}

This is how we could perform operations in the database.

using LiteDB;

// open the database (or create it if it does not exist)
var db = new LiteDatabase("myDatabase.db");

// get a collection of documents
var collection = db.GetCollection("users");

// add a new document
var customer = new Customer
{ 
	Name = "John Doe", 
	Phones = new string[] { "8000-0000", "9000-0000" }, 
	Age = 39,
	IsActive = true
};   
collection.Insert(user);

// update a document
customer.Name = "Joana Doe";
col.Update(customer);

We could also work directly with BsonDocuments (which I do not particularly recommend) as follows

using LiteDB;

// open the database (or create it if it does not exist)
var db = new LiteDatabase("myDatabase.db");

// get a collection of documents
var collection = db.GetCollection("users");

// add a new document
var user = new BsonDocument
{
    { "name", "John Doe" },
    { "age", 30 },
    { "email", "johndoe@example.com" }
};

collection.Insert(user);

LiteDB is Open Source, and all the code and documentation is available on the project’s page https://www.litedb.org/ and its repository https://github.com/mbdavid/litedb