Small but Beautiful, Powerful Yet Efficient: Revealing a Tiny NoSQL Database in the .NET Ecosystem

Small but Beautiful, Powerful Yet Efficient: Revealing a Tiny NoSQL Database in the .NET Ecosystem

In the world of .NET, choosing the right database is crucial. Today, let's uncover a lightweight NoSQL database—LiteDB. It is small but powerful, providing fast and flexible data storage solutions for your projects. Whether you are a beginner or an experienced developer, LiteDB will be your reliable assistant!

Last updated 3/8/2024 5:14 AM
开源项目甄选
5 min read
Category
.NET
Tags
.NET C# Database LiteDB NoSQL

Introduction

In the world of .NET, database selection is crucial. Today, let's unveil a lightweight NoSQL database—LiteDB. It is compact yet powerful, providing fast and flexible data storage solutions for your projects. Whether you are a beginner or an experienced developer, LiteDB will be your capable assistant!

LiteDB Overview

LiteDB is an open-source, embedded NoSQL database, written entirely in C# managed code, specifically designed for .NET. It stores data in BSON (Binary JSON) format, supports rich query operations, and does not require installing or managing a complex server. LiteDB is ideal for small projects, desktop applications, and data storage needs in microservice architectures.

LiteDB Features

  • Simple API, similar to MongoDB
  • 100% C# code for .NET 4.5 / NETStandard 1.3/2.0 in a single DLL (less than 450kb)
  • Thread-safe
  • Data recovery after write failures (WAL log file)
  • Data file encryption using DES (AES) encryption technology
  • Map POCO classes to BsonDocument using attributes or Fluent mapper API
  • Store files and stream data (like GridFS in MongoDB)
  • Single data file storage (like SQLite)
  • Index document fields for fast searches
  • LINQ support for queries
  • SQL-like commands for accessing/transforming data
  • Open source and free for everyone – including commercial use

LiteDB Highlights

Lightweight: LiteDB requires no server installation, integrates directly into your .NET project, has a small footprint, and runs fast.

High Performance: Supports indexes, query optimization, and asynchronous operations to ensure efficient data reads and writes.

Easy to Use: Provides a simple API and rich documentation support, making it easy to get started.

ACID Transaction Support: Ensures data consistency and integrity.

Cross-platform: LiteDB can run on multiple platforms including Windows, Linux, and macOS.

Beautiful UI Support: LiteDB Studio – a beautiful user interface for data access.

How to Use LiteDB

Installation: Easily install LiteDB via NuGet package manager.

Create a Database: Create a LiteDatabase instance in your project, specifying the database file path.

Define Models: Create C# classes to define your data models.

Store and Query Data: Use the API provided by LiteDB to store, query, and update data.

Beautiful UI

New UI for Lite.Studio to Manage and Visualize Databases

Features

LiteDB supports an SQL-like language for data and structure operations. You can insert, update, delete, or query the database using a very similar SQL relational language.

LINQ expressions (lambda functions) can be used to create fluent API queries in C# code.

The new LiteDB.Studio management tool supports all SQL commands.

You can also obtain a detailed EXPLAIN PLAN from the query engine to check whether the written query will run with optimal performance.

Practical Example

A simple practical example demonstrates how to use LiteDB to perform CRUD operations in a .NET project.

// Create your POCO class
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; }
}

// Open database (or create if doesn't exist)
using(var db = new LiteDatabase(@"MyData.db"))
{
    // Get customer collection
    var col = db.GetCollection<Customer>("customers");

    // Create your new customer instance
    var customer = new Customer
    {
        Name = "John Doe",
        Phones = new string[] { "8000-0000", "9000-0000" },
        Age = 39,
        IsActive = true
    };

    // Create unique index in Name field
    col.EnsureIndex(x => x.Name, true);

    // Insert new customer document (Id will be auto-incremented)
    col.Insert(customer);

    // Update a document inside a collection
    customer.Name = "Joana Doe";

    col.Update(customer);

    // Use LINQ to query documents (with no index)
    var results = col.Find(x => x.Age > 20);
}

Using more complex data models

// DbRef for cross references
public class Order
{
    public ObjectId Id { get; set; }
    public DateTime OrderDate { get; set; }
    public Address ShippingAddress { get; set; }
    public Customer Customer { get; set; }
    public List<Product> Products { get; set; }
}

// Re-use mapper from global instance
var mapper = BsonMapper.Global;

// "Products" and "Customer" are from other collections (not embedded documents)
mapper.Entity<Order>()
    .DbRef(x => x.Customer, "customers")   // 1 to 1/0 reference
    .DbRef(x => x.Products, "products")    // 1 to Many reference
    .Field(x => x.ShippingAddress, "addr"); // Embedded sub document

using(var db = new LiteDatabase("MyOrderDatafile.db"))
{
    var orders = db.GetCollection<Order>("orders");

    // When querying Order, include references
    var query = orders
        .Include(x => x.Customer)
        .Include(x => x.Products) // 1 to many reference
        .Find(x => x.OrderDate <= DateTime.Now);

    // Each instance of Order will load Customer/Products references
    foreach(var order in query)
    {
        var name = order.Customer.Name;
        ...
    }
}

Summary

LiteDB, as a lightweight NoSQL database, has gained widespread recognition in the .NET development field for its compact size, high performance, and ease of use. Whether you are a beginner or an experienced developer, you can try using LiteDB to provide data storage solutions for your projects.

Source Code

https://github.com/mbdavid/LiteDB

Keep Exploring

Related Reading

More Articles