NoSQL using LiteDB example

I had posted a previous example using SQLlite. Often applications need a way to store unstructured or semi-structured data. Using a NoSQL database could be a solution.

Here is an example using LiteDB, LiteDB offers several features that makes it useful for an embedded device.

Requires the LiteDB NuGet


using LiteDB;

var dataFile = "SensorData.db";

// Open database (or create if doesn't exist)
using (var db = new LiteDatabase(dataFile))
{
    // Get a collection (or create, if doesn't exist)
    var col = db.GetCollection<Sensor>("sensors");

    // Create a new sensor instance
    var sensor = new Sensor
    {
        Name = "MEMS12",
        ConfigValues = new string[] { "0x00", "0xAA" },
        IsActive = true
    };

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

    // Update a document inside a collection
    sensor.Name = "MEMS13";

    col.Update(sensor);

    // Index document using document Name property
    col.EnsureIndex(x => x.Name);

    // Use LINQ to query documents (filter, sort, transform)
    var results = col.Query()
        .Where(x => x.Name.StartsWith("M"))
        .OrderBy(x => x.Name)
        .Select(x => new { x.Name, NameUpper = x.Name.ToUpper() })
        .Limit(10)
        .ToList();

    foreach(var memsSensor in results)
    {
        Console.WriteLine(memsSensor.Name);
    }
    
    // Create an index on the ConfigValues property
    col.EnsureIndex(x => x.ConfigValues);

    // Query by config value
    var r = col.FindOne(x => x.ConfigValues.Contains("0xAA"));

    Console.WriteLine(r.Name);
}

//delete the data file when done
FileInfo dbFile = new FileInfo(dataFile);
try
{
    if (dbFile.Exists)
    {
        dbFile.Delete();
    }
}
catch(Exception ex)
{
    Console.WriteLine("Unable to delete the data file"+ex.Message);
}

//Define Sensor class
public class Sensor
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public required string[] ConfigValues { get; set; }
    public bool IsActive { get; set; }
}


Adapted from the LiteDB documentation

1 Like

Thanks, I think we need add these to our docs

Document about SQL · Issue #754 · ghi-electronics/Documentation (github.com)

Why not just store it in an XML file?

Why did this appear five years after the last posting? Glitch in the Matrix?