### FileStorage C# Examples Source: https://github.com/litedb-org/litedb/wiki/FileStorage Demonstrates common operations for uploading, finding, and downloading files using LiteDB's FileStorage in C#. ```csharp // Upload a file from file system db.FileStorage.Upload("$/photos/2014/picture-01.jpg", @"C:\\Temp\\picture-01.jpg"); ``` ```csharp // Upload a file from a Stream db.FileStorage.Upload("$/photos/2014/picture-01.jpg", "picture-01.jpg", stream); ``` ```csharp // Find file reference only - returns null if not found LiteFileInfo file = db.FileStorage.FindById("$/photos/2014/picture-01.jpg"); ``` ```csharp // Now, load binary data and save to file system file.SaveAs(@"C:\\Temp\\new-picture.jpg"); ``` ```csharp // Or get binary data as Stream and copy to another Stream file.CopyTo(Response.OutputStream); ``` ```csharp // Find all files references in a "directory" var files = db.FileStorage.Find("$/photos/2014/"); ``` -------------------------------- ### Get and Use LiteCollection or BsonDocument Source: https://github.com/litedb-org/litedb/wiki/Collections Demonstrates how to get a collection instance for both strong-typed objects and generic BsonDocuments, including inserting and indexing. Collections are auto-created if they don't exist upon insertion. ```C# using(var db = new LiteDatabase("mydb.db")) { // Get collection instance var col = db.GetCollection("customer"); // Insert document to collection - if collection do not exists, create now col.Insert(new Customer { Id = 1, Name = "John Doe" }); // Create, if not exists, new index on Name field col.EnsureIndex(x => x.Name); // Now, search for document your document var customer = col.FindOne(x => x.Name == "john doe"); } ``` ```C# using(var db = new LiteDatabase("mydb.db")) { // Get collection instance var col = db.GetCollection("customer"); // Insert document to collection - if collection do not exists, create now col.Insert(new BsonDocument().Add("_id", 1).Add("Name", "John Doe")); // Create, if not exists, new index on Name field col.EnsureIndex("Name"); // Now, search for document your document var customer = col.FindOne(Query.EQ("Name", "john doe")); } ``` -------------------------------- ### Get Query Execution Plan Source: https://context7.com/litedb-org/litedb/llms.txt Shows how to retrieve the execution plan for a query using the GetPlan() method, useful for performance analysis. ```csharp // Get query execution plan BsonDocument plan = col.Query() .Where(x => x.Name == "Alice") .GetPlan(); Console.WriteLine(plan); ``` -------------------------------- ### Basic LiteDB Operations in C# Source: https://github.com/litedb-org/litedb/wiki/Getting-Started Demonstrates creating a POCO class, opening a database, getting a collection, inserting, updating, indexing, and querying documents using LINQ. Ensure the database path is writable. ```C# // Create your POCO class entity public class Customer { public int Id { get; set; } public string Name { 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(@"C:\\Temp\MyData.db")) { // Get a collection (or create, if doesn't exist) var col = db.GetCollection("customers"); // Create your new customer instance var customer = new Customer { Name = "John Doe", Phones = new string[] { "8000-0000", "9000-0000" }, IsActive = 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); // Index document using document Name property col.EnsureIndex(x => x.Name); // Use LINQ to query documents var results = col.Find(x => x.Name.StartsWith("Jo")); // Let's create an index in phone numbers (using expression). It's a multikey index col.EnsureIndex(x => x.Phones, "$.Phones[*]"); // and now we can query phones var r = col.FindOne(x => x.Phones.Contains("8888-5555")); } ``` -------------------------------- ### Starts With Query Source: https://github.com/litedb-org/litedb/wiki/Queries Find documents where a string field begins with a specified prefix. This query is valid only for string data types and can utilize indexes. ```C# var results = col.Find(Query.StartsWith("Name", "Jo")); ``` -------------------------------- ### LiteRepository Basic Operations and Querying Source: https://github.com/litedb-org/litedb/wiki/Repository-Pattern Demonstrates basic Insert, Delete, and fluent Query operations with LiteRepository. Includes examples of including related data, filtering by date and boolean properties, and limiting results. Conditional filtering is also shown. ```C# using(var db = new LiteRepository(connectionString)) { // simple access to Insert/Update/Upsert/Delete db.Insert(new Product { ProductName = "Table", Price = 100 }); db.Delete(x => x.Price == 100); // query using fluent query var result = db.Query() .Include(x => x.Customer) // add dbref 1x1 .Include(x => x.Products) // add dbref 1xN .Where(x => x.Date == DateTime.Today) // use indexed query .Where(x => x.Active) // used indexes query .ToList(); var p = db.Query() .Where(x => x.ProductName.StartsWith("Table")) .Where(x => x.Price < 200) .Limit(10) .ToEnumerable(); var c = db.Query() .Where(txtName.Text != null, x => x.Name == txtName.Text) // conditional filter .ToList(); } ``` -------------------------------- ### Example LiteDB Document Structure Source: https://github.com/litedb-org/litedb/wiki/Data-Structure Illustrates the structure of a typical document stored in LiteDB, including nested documents and arrays. ```javascript { _id: 1, name: { first: "John", last: "Doe" }, age: 37, salary: 3456.0, createdDate: { $date: "2014-10-30T00:00:00.00Z" }, phones: ["8000-0000", "9000-0000"] } ``` -------------------------------- ### Store and Query Documents in LiteDB Source: https://github.com/litedb-org/litedb/blob/master/README.md Demonstrates basic CRUD operations and LINQ querying with LiteDB. Ensure the LiteDB NuGet package is installed. Indexes can be created for performance. ```csharp 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("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); } ``` -------------------------------- ### LiteDB LINQ Query Examples Source: https://github.com/litedb-org/litedb/wiki/Queries Demonstrates how to use LINQ expressions for querying strongly-typed documents in LiteDB. These expressions are converted to `Query` objects behind the scenes. ```C# col.Find(x => x.Name == "John Doe") // Query.EQ("Name", "John Doe") ``` ```C# col.Find(x => x.Age > 30) // Query.GT("Age", 30) ``` ```C# col.Find(x => x.Name.StartsWith("John") && x.Age > 30) // Query.And(Query.StartsWith("Name", "John"), Query.GT("Age", 30)) ``` ```C# // where PhoneNumbers is string[] col.Find(x => x.PhoneNumbers.Contains("555-1234")) // Query.EQ("PhoneNumbers", "555-1234") ``` ```C# // create index on Number inside phone array col.EnsureIndex(x => x.Phones[0].Number); // ignore 0 index: it's just a syntax to access child // db.EnsureIndex("col", "Phones[*].Number", false, "$.Phones[*].Number) col.Find(x => x.Phones.Select(z => z.Number == "555-1234")) // another way to access child // Query.EQ("Phones[*].Numbers", "555-1234") ``` ```C# col.Find(x => !(x.Age > 30)) // Query.Not(Query.GT("Age", 30)) ``` -------------------------------- ### Fluent Mapping with EntityBuilder Source: https://github.com/litedb-org/litedb/wiki/Object-Mapping Use `EntityBuilder` to configure custom mappings for your entities. This example shows how to set the document ID, ignore a property, and rename a field. ```csharp var mapper = BsonMapper.Global; mapper.Entity() .Id(x => x.MyCustomKey) // set your document ID .Ignore(x => x.DoNotSerializeThis) // ignore this property (do not store) .Field(x => x.CustomerName, "cust_name"); // rename document field ``` -------------------------------- ### Get Schema-less BsonDocument Collection Source: https://context7.com/litedb-org/litedb/llms.txt Retrieves a collection that stores BsonDocuments, allowing for schema-less data storage. Collections are created automatically on first write. ```csharp // Schema-less BsonDocument collection var raw = db.GetCollection("customers"); ``` -------------------------------- ### Find Files in LiteDB Source: https://github.com/litedb-org/litedb/wiki/Shell Lists all files in the database or files whose fileId starts with the provided parameter. Use without parameters to list all files. ```shell fs.find ``` ```shell fs.find $/photos/ ``` -------------------------------- ### Define Strongly-Typed Document and Collections Source: https://github.com/litedb-org/litedb/wiki/Object-Mapping Define a POCO class for strongly-typed documents and retrieve a LiteCollection instance for it. Alternatively, get a schemeless collection where defaults to BsonDocument. ```C# public class Customer { public ObjectId CustomerId { get; set; } public string Name { get; set; } public DateTime CreateDate { get; set; } public List Phones { get; set; } public bool IsActive { get; set; } } var typedCustomerCollection = db.GetCollection("customer"); var schemelessCollection = db.GetCollection("customer"); // is BsonDocument ``` -------------------------------- ### Update Document with Expression Source: https://github.com/litedb-org/litedb/wiki/Expressions Example of updating a document's field using an expression within the `update` shell command. This allows for dynamic updates based on existing data. ```Shell db.customers.update $.Name = LOWER($.Name) where _id = 1 ``` -------------------------------- ### Get Maximum Value from Indexed Field Source: https://github.com/litedb-org/litedb/wiki/Shell Retrieves the highest value present in an indexed field within a collection. ```shell db.customer.max _id ``` ```shell db.customer.max Age ``` -------------------------------- ### Get Minimum Value from Indexed Field Source: https://github.com/litedb-org/litedb/wiki/Shell Retrieves the lowest value present in an indexed field within a collection. ```shell db.customer.min _id ``` ```shell db.customer.min Age ``` -------------------------------- ### Open LiteDatabase with Connection String Options Source: https://context7.com/litedb-org/litedb/llms.txt Demonstrates opening a LiteDB database using a connection string with various options like filename, password, connection type, initial size, and upgrade flag. Always wrap in a 'using' block. ```csharp using var db = new LiteDatabase( "filename=app.db;password=s3cr3t;connection=shared;initial size=10MB;upgrade=true"); ``` -------------------------------- ### Build and Use BsonDocument and BsonValue Source: https://context7.com/litedb-org/litedb/llms.txt Demonstrates manual construction of BsonDocument, implicit conversions to BsonValue, type checking, extraction, handling missing fields, and JSON serialization/deserialization. ```csharp // Build a BsonDocument manually var doc = new BsonDocument { ["_id"] = ObjectId.NewObjectId(), ["name"] = "Alice", ["age"] = 30, ["active"] = true, ["score"] = 9.5, ["tags"] = new BsonArray { "vip", "early-adopter" }, ["address"] = new BsonDocument { ["city"] = "Paris", ["zip"] = "75001" }, ["created"] = DateTime.UtcNow }; // BsonValue implicit conversions BsonValue strVal = "hello"; BsonValue intVal = 42; BsonValue boolVal = true; // Type checks and extraction if (doc["age"].IsInt32) int age = doc["age"].AsInt32; string name = doc["name"].AsString; DateTime dt = doc["created"].AsDateTime; BsonArray tags = doc["tags"].AsArray; // Missing fields return BsonValue.Null (never throws) BsonValue missing = doc["nonexistent"]; // == BsonValue.Null // JSON serialization string json = JsonSerializer.Serialize(doc, pretty: true); BsonValue back = JsonSerializer.Deserialize(json); ``` -------------------------------- ### Fluent Query Builder with Sorting and Paging Source: https://context7.com/litedb-org/litedb/llms.txt Demonstrates how to use the fluent query builder to filter, sort, and paginate results. Requires a LiteDatabase instance and a collection. ```csharp using var db = new LiteDatabase("app.db"); var col = db.GetCollection("customers"); // Fluent query with sorting and paging List page = col.Query() .Where(x => x.IsActive) .OrderBy(x => x.Name) .Skip(20) .Limit(10) .ToList(); ``` -------------------------------- ### Query with Auto-Loading References Source: https://github.com/litedb-org/litedb/wiki/DbRef Demonstrates how to use the Include method to automatically load the referenced Customer object when querying an Order. ```csharp var orders = db.GetCollection("orders"); var order1 = orders .Include(x => x.Customer) .FindById(1); ``` -------------------------------- ### Concatenate String with Expression Source: https://github.com/litedb-org/litedb/wiki/Expressions Example of concatenating a string literal with a document field using an expression in the shell. This is useful for creating formatted output. ```Shell db.dummy.select 'My Id is ' + $._id ``` -------------------------------- ### Open LiteDatabase with Simple File Path Source: https://context7.com/litedb-org/litedb/llms.txt Opens a LiteDB database using a simple file path. The file will be created if it does not exist. Always wrap in a 'using' block. ```csharp // Simple file path (creates the file if it doesn't exist) using var db = new LiteDatabase("MyData.db"); ``` -------------------------------- ### BsonMapper: Use Custom Mapper in Database Source: https://context7.com/litedb-org/litedb/llms.txt Demonstrates how to create and use a custom BsonMapper instance for a specific LiteDatabase instance, rather than configuring the global mapper. ```csharp // Use the custom mapper in a specific database only var mapper = new BsonMapper(); mapper.UseCamelCase(); using var db = new LiteDatabase("app.db", mapper); ``` -------------------------------- ### Map List of References Source: https://github.com/litedb-org/litedb/wiki/DbRef Defines Product and Order classes and maps the List property to the 'products' collection using the fluent API. ```csharp public class Product { public int ProductId { get; set; } public string Name { get; set; } public decimal Price { get; set; } } public class Order { public int OrderId { get; set; } public DateTime OrderDate { get; set; } public List Products { get; set; } } BsonMapper.Global.Entity() .DbRef(x => x.Products, "products"); ``` -------------------------------- ### Get Typed LiteCollection with Inferred Name Source: https://context7.com/litedb-org/litedb/llms.txt Retrieves a strongly-typed ILiteCollection where the collection name is automatically inferred from the class name. Collections are created automatically on first write. ```csharp // Collection name inferred from type name → "Customer" var col2 = db.GetCollection(); ``` -------------------------------- ### Define Customer and Order Classes Source: https://github.com/litedb-org/litedb/wiki/DbRef Basic C# classes for Customer and Order entities without explicit reference mapping. ```csharp public class Customer { public int CustomerId { get; set; } public string Name { get; set; } } public class Order { public int OrderId { get; set; } public Customer Customer { get; set; } } ``` -------------------------------- ### Execute a SUM Expression Source: https://github.com/litedb-org/litedb/wiki/Expressions Demonstrates how to create and execute a BsonExpression to calculate a sum from document fields. Ensure the document structure matches the expression's path. ```C# var expr = new BsonExpression("SUM($.Items[*].Unity * $.Items[*].Price)"); var total = expr.Execute(doc, true).First().AsDecimal; ``` -------------------------------- ### Get Typed LiteCollection with Auto-Id Source: https://context7.com/litedb-org/litedb/llms.txt Retrieves a strongly-typed ILiteCollection for a given class, specifying the collection name and the auto-incrementing ID type. Collections are created automatically on first write. ```csharp public class Customer { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public bool IsActive { get; set; } public DateTime CreatedAt { get; set; } } using var db = new LiteDatabase("app.db"); // Named collection, int auto-id var col = db.GetCollection("customers", BsonAutoId.Int32); ``` -------------------------------- ### Array Element Query Source: https://github.com/litedb-org/litedb/wiki/Queries Query documents based on a field within an array of embedded documents. This example finds documents where any element in the 'Products' array has a 'Price' greater than 100. ```C# // Query using multikey index (where products are an array of embedded documents) var results = col.Find(Query.GT("Products[*].Price", 100)) ``` -------------------------------- ### Select New Document with Expression Source: https://github.com/litedb-org/litedb/wiki/Expressions Demonstrates creating a new document structure with transformed data using the `select` shell command and expressions. This is useful for shaping query results. ```Shell db.customers.select { upper_titles: ARRAY(UPPER($.Books[*].Title)) } where $.Name startswith "John" ``` -------------------------------- ### Manage Files with LiteStorage Source: https://context7.com/litedb-org/litedb/llms.txt Handles binary file storage within the database, chunked into 1 MB pieces. Supports uploading from paths or streams, downloading, streaming reads, metadata management, and finding/deleting files. Custom file ID types and collection names are supported. ```csharp using var db = new LiteDatabase("app.db"); // Upload from a local file path LiteFileInfo info = db.FileStorage.Upload("$/images/logo.png", @"C:\\assets\\logo.png"); // Upload from a Stream using var stream = File.OpenRead(@"C:\\report.pdf"); db.FileStorage.Upload("$/reports/2024/q1.pdf", "q1.pdf", stream); // Download to a Stream using var output = File.Create(@"C:\\copy\\logo.png"); db.FileStorage.Download("$/images/logo.png", output); // Download to a local file db.FileStorage.Download("$/reports/2024/q1.pdf", @"C:\\copy\\q1.pdf", overwritten: true); // Open for streaming read using LiteFileStream fs = db.FileStorage.OpenRead("$/images/logo.png"); // use fs as a regular Stream... // Set / update metadata db.FileStorage.SetMetadata("$/images/logo.png", new BsonDocument { ["author"] = "design-team" }); // Find by predicate IEnumerable> images = db.FileStorage.Find("$.filename LIKE '%.png'"); // Find all foreach (var file in db.FileStorage.FindAll()) Console.WriteLine($"{file.Id} {file.Length} bytes {file.UploadDate}"); // Check existence / delete if (db.FileStorage.Exists("$/images/logo.png")) db.FileStorage.Delete("$/images/logo.png"); // Custom FileId type and collection names ILiteStorage gs = db.GetStorage("my_files", "my_chunks"); gs.Upload(Guid.NewGuid(), "photo.jpg", photoStream); ``` -------------------------------- ### Serialize Object to BSON Document and then to JSON Source: https://github.com/litedb-org/litedb/wiki/Data-Structure Demonstrates converting a C# object to a BSON document using BsonMapper and then serializing it to a JSON string using JsonSerializer. Requires LiteDB and System.Text.Json or similar. ```csharp var customer = new Customer { Id = 1, Name = "John Doe" }; var doc = BsonMapper.Global.ToDocument(customer); var jsonString = JsonSerialize.Serialize(doc, pretty, includeBinaryData); ``` -------------------------------- ### Open LiteDatabase with Full Connection String Source: https://context7.com/litedb-org/litedb/llms.txt Opens a LiteDB database using a full connection string with various options. Always wrap in a 'using' block. ```csharp // Full connection string with options using var db = new LiteDatabase("filename=MyData.db;password=secret;connection=shared;initial size=5MB"); ``` -------------------------------- ### Configure BsonMapper to Use Lowercase Delimiters Source: https://github.com/litedb-org/litedb/wiki/Object-Mapping Configure the global BsonMapper to use lowercase delimiters for field names. This affects how property names are converted to document field names, for example, 'FirstName' becomes 'first_name'. ```C# BsonMapper.Global.UseLowerCaseDelimiter('_'); public class Customer { public int CustomerId { get; set; } public string FirstName { get; set; } [BsonField("customerLastName")] public string LastName { get; set; } } var doc = BsonMapper.Global.ToDocument(new Customer { FirstName = "John", LastName = "Doe" }); var id = doc["_id"].AsInt; var john = doc["first_name"].AsString; var doe = doc["customerLastName"].AsString; ``` -------------------------------- ### LiteDB FileStorage Operations in C# Source: https://github.com/litedb-org/litedb/wiki/Getting-Started Demonstrates uploading a file from the file system to the database and downloading it later using LiteDB's FileStorage API. Ensure the file paths are valid. ```C# // Upload a file from file system to database db.FileStorage.Upload("my-photo-id", @"C:\\Temp\picture-01.jpg"); // And download later db.FileStorage.Download("my-photo-id", @"C:\\Temp\copy-of-picture-01.jpg"); ``` -------------------------------- ### Generate and Use ObjectId in C# Source: https://github.com/litedb-org/litedb/wiki/Data-Structure Demonstrates how to generate a new ObjectId, retrieve its creation time, and create an ObjectId from a hex string. ObjectIds are sequential and suitable for indexing. ```C# var id = ObjectId.NewObjectId(); // You can get creation datetime from an ObjectId var date = id.CreationTime; // ObjectId is represented in hex value Debug.WriteLine(id); "507h096e210a18719ea877a2" // Create an instance based on hex representation var nid = new ObjectId("507h096e210a18719ea877a2"); ``` -------------------------------- ### Manage Transactions with BeginTrans, Commit, Rollback Source: https://context7.com/litedb-org/litedb/llms.txt Shows how to use transactions for atomic operations. Transactions are per-thread and auto-commit if not explicitly managed. Ensure to rollback on exceptions. ```csharp using var db = new LiteDatabase("app.db"); var orders = db.GetCollection("orders"); var products = db.GetCollection("products"); db.BeginTrans(); try { orders.Insert(new Order { OrderId = Guid.NewGuid(), Total = 199.99m }); // Simulate stock decrement var product = products.FindOne(x => x.Sku == "WIDGET-01"); product.Stock -= 1; products.Update(product); db.Commit(); } catch (Exception ex) { db.Rollback(); Console.WriteLine($"Transaction rolled back: {ex.Message}"); } ``` -------------------------------- ### Query with Linq Syntax for Includes Source: https://github.com/litedb-org/litedb/wiki/DbRef Uses Linq syntax with the Include method on a query object to load referenced Customer and Products. ```csharp db.Query() .Include(x => x.Customer) .Include(x => x.Products) .ToList(); ``` -------------------------------- ### Download File from LiteDB Source: https://github.com/litedb-org/litedb/wiki/Shell Downloads an existing database file to a local file path. Use this to retrieve stored files. ```shell fs.download my-file copy-picture.jpg ``` ```shell fs.download $/photos/pic-001 C:\Temp\mypictures\copy-picture-1.jpg ``` -------------------------------- ### General Shell Commands Source: https://github.com/litedb-org/litedb/wiki/Shell Provides essential commands for interacting with the LiteDB shell, including help, opening/closing databases, and managing command output. ```shell help [full] ``` ```shell open ``` ```shell close ``` ```shell pretty ``` ```shell ed ``` ```shell run ``` ```shell spool [on|off] ``` ```shell timer ``` ```shell -- ``` ```shell // ``` ```shell upgrade // ``` ```shell version ``` ```shell quit ``` -------------------------------- ### List All Indexes on Collection Source: https://github.com/litedb-org/litedb/wiki/Shell Displays all indexes currently defined for a specified collection. ```shell db.customers.indexes ``` -------------------------------- ### Open LiteDatabase with ConnectionString Object Source: https://context7.com/litedb-org/litedb/llms.txt Opens a LiteDB database using a ConnectionString object for programmatic configuration. Always wrap in a 'using' block. ```csharp // With a ConnectionString object var cs = new ConnectionString { Filename = "MyData.db", Password = "secret", ReadOnly = false, Upgrade = true, // upgrade from older LiteDB format AutoRebuild = true // auto-rebuild if last close was abnormal }; using var db = new LiteDatabase(cs); ``` -------------------------------- ### Execute SQL-Like Commands with ILiteDatabase.Execute Source: https://context7.com/litedb-org/litedb/llms.txt Utilizes the `Execute` method for SQL-style commands including SELECT, INSERT, UPDATE, DELETE, index management, collection operations, and CHECKPOINT. Supports positional parameters for safety. ```csharp using var db = new LiteDatabase("app.db"); // SELECT using var reader = db.Execute("SELECT $ FROM customers WHERE $.IsActive = true LIMIT 10"); while (reader.Read()) Console.WriteLine(reader.Current["name"].AsString); // INSERT with positional parameters (@0, @1, ...) db.Execute("INSERT INTO logs VALUES { msg: @0, ts: @1 }", "App started", DateTime.Now); // UPDATE db.Execute("UPDATE customers SET $.Name = UPPER($.Name) WHERE $.IsActive = true"); // DELETE db.Execute("DELETE customers WHERE $.CreatedAt < @0", DateTime.Now.AddYears(-5)); // CREATE / DROP INDEX db.Execute("CREATE INDEX idx_email ON customers($.Email)"); db.Execute("DROP INDEX customers.idx_email"); // SELECT INTO – copy results to a new collection db.Execute("SELECT $ INTO archive FROM customers WHERE $.IsActive = false"); // CHECKPOINT – flush WAL log to data file db.Execute("CHECKPOINT"); ``` -------------------------------- ### BsonMapper: Configure Serialization Options Source: https://context7.com/litedb-org/litedb/llms.txt Sets global options for the BSON mapper, such as whether to serialize null values, represent enums as integers, or convert empty strings to null. ```csharp BsonMapper.Global.SerializeNullValues = true; BsonMapper.Global.EnumAsInteger = true; BsonMapper.Global.EmptyStringToNull = false; ``` -------------------------------- ### ForUpdate: Lock Collection for Writing Source: https://context7.com/litedb-org/litedb/llms.txt Demonstrates using the ForUpdate() method to lock the collection in write mode during the query execution, ensuring data consistency. ```csharp // ForUpdate: lock collection in write mode during query var forUpdate = col.Query() .Where(x => x.IsActive) .ForUpdate() .ToList(); ``` -------------------------------- ### Index Management Source: https://context7.com/litedb-org/litedb/llms.txt Explicitly create indexes using `EnsureIndex` for better performance and optionally enforce unique constraints. Indexes can be dropped using `DropIndex`. ```APIDOC ## Index Management — `EnsureIndex` / `DropIndex` Indexes are created on-the-fly when needed, but explicit indexes deliver better performance. Unique indexes enforce no-duplicate constraints. ```csharp using var db = new LiteDatabase("app.db"); var col = db.GetCollection("customers"); // Simple field index via LINQ col.EnsureIndex(x => x.Name); // Unique index col.EnsureIndex(x => x.Email, unique: true); // Named index with BsonExpression (useful for compound/computed values) col.EnsureIndex("idx_name_lower", "LOWER($.Name)"); // Named index via LINQ with unique constraint col.EnsureIndex("idx_email", x => x.Email, unique: true); // Drop an index by name col.DropIndex("idx_email"); // Attribute-based indexing (declared on the POCO) public class Product { public int Id { get; set; } [BsonIndex] // non-unique index public string Sku { get; set; } [BsonIndex(true)] // unique index (bool overload) public string Barcode { get; set; } } ``` ``` -------------------------------- ### BsonMapper: Fluent Entity Configuration Source: https://context7.com/litedb-org/litedb/llms.txt Provides an alternative to attributes for configuring entity mapping, including ID, fields, ignored properties, and database references. ```csharp // Fluent entity configuration (alternative to attributes) BsonMapper.Global.Entity() .Id(o => o.OrderId, autoId: false) .Field(o => o.CustomerId, "cust_id") .Ignore(o => o.TempNote) .DbRef(o => o.Customer, "customers"); ``` -------------------------------- ### Upgrade Datafile via Connection String Source: https://github.com/litedb-org/litedb/wiki/Update-Datafile Use the 'upgrade=true' parameter in the connection string to automatically upgrade the datafile when opening it with LiteDB v4.x. ```csharp var db = new LiteDatabase("filename=old.db;upgrade=true"); ``` -------------------------------- ### Create Index with Expression Source: https://github.com/litedb-org/litedb/wiki/Shell Creates an index on a collection field using a custom expression, such as applying a function like `LOWER`. ```shell db.customers.ensureIndex NameLower using LOWER($.Name) ``` -------------------------------- ### LiteDatabase API Instance Methods Source: https://github.com/litedb-org/litedb/wiki/Collections Methods available on the LiteDatabase instance for managing collections. ```APIDOC ## GetCollection ### Description Returns a new instance of `LiteCollection`. If `` is omitted, `` defaults to `BsonDocument`. This is the primary method for accessing a collection. ### Method `GetCollection(string collectionName)` `GetCollection(string collectionName)` ### Endpoint N/A (SDK Method) ## RenameCollection ### Description Renames an existing collection. ### Method `RenameCollection(string oldName, string newName)` ### Endpoint N/A (SDK Method) ## CollectionExists ### Description Checks if a collection with the specified name exists in the database. ### Method `CollectionExists(string collectionName)` ### Endpoint N/A (SDK Method) ## GetCollectionNames ### Description Retrieves a list of all collection names currently in the database. ### Method `GetCollectionNames()` ### Endpoint N/A (SDK Method) ## DropCollection ### Description Deletes a collection, including all its documents and indexes. ### Method `DropCollection(string collectionName)` ### Endpoint N/A (SDK Method) ``` -------------------------------- ### Query with Path Syntax for Includes Source: https://github.com/litedb-org/litedb/wiki/DbRef Uses path syntax with an array of strings to include multiple levels or types of references in a query. ```csharp orders.Include(new string[] { "$.Customer", "$.Products[*]" }); ``` -------------------------------- ### LiteCollection API Instance Methods Source: https://github.com/litedb-org/litedb/wiki/Collections Methods available on a LiteCollection instance for document and index management. ```APIDOC ## Insert ### Description Inserts a new document or an enumerable collection of documents into the current collection. If documents lack an `_id` field, LiteDB generates one using `ObjectId`. ### Method `Insert(T document)` `Insert(IEnumerable documents)` ### Endpoint N/A (SDK Method) ## InsertBulk ### Description Efficiently inserts a large volume of documents by breaking them into batches and managing transactions per batch. This method is optimized for low memory usage by clearing its cache after each batch. ### Method `InsertBulk(IEnumerable documents)` ### Endpoint N/A (SDK Method) ## Update ### Description Updates a single document identified by its `_id` field. Returns `false` if the document is not found. ### Method `Update(T document)` ### Endpoint N/A (SDK Method) ## Delete ### Description Deletes a document based on its `_id` or by the results of a query. Returns `false` if no document is found or deleted. ### Method `Delete(Query query)` `Delete(BsonValue id)` ### Endpoint N/A (SDK Method) ## Find ### Description Retrieves documents from the collection that match the specified LiteDB queries. ### Method `Find(Query query)` `Find(Query query, int limit, int offset)` ### Endpoint N/A (SDK Method) ## EnsureIndex ### Description Creates a new index on a specified field within the collection. This can improve query performance. ### Method `EnsureIndex(string fieldName)` `EnsureIndex(Expression> expression)` ### Endpoint N/A (SDK Method) ## DropIndex ### Description Removes an existing index from the collection. ### Method `DropIndex(string fieldName)` ### Endpoint N/A (SDK Method) ``` -------------------------------- ### LiteRepository High-Level API Source: https://context7.com/litedb-org/litedb/llms.txt Use LiteRepository for a simplified, generic API without explicit collection references. Supports insert, upsert, update, delete, fetch, and querying. ```csharp using var repo = new LiteRepository("app.db"); // Insert repo.Insert(new Customer { Name = "Alice" }); repo.Insert(new[] { new Customer { Name = "Bob" }, new Customer { Name = "Carol" } }); // Upsert repo.Upsert(new Customer { Id = 1, Name = "Alice Updated" }); // Update repo.Update(new Customer { Id = 1, Name = "Alice v2" }); // Delete by id repo.Delete(new BsonValue(1)); // Delete by predicate repo.DeleteMany(x => !x.IsActive); // Fetch list List active = repo.Fetch(x => x.IsActive); // First / FirstOrDefault / Single / SingleOrDefault Customer alice = repo.FirstOrDefault(x => x.Name == "Alice"); Customer byId = repo.SingleById(new BsonValue(1)); // Fluent query via Query() List result = repo.Query() .Where(x => x.IsActive) .OrderBy(x => x.Name) .Limit(5) .ToList(); // EnsureIndex repo.EnsureIndex(x => x.Email, unique: true); ``` -------------------------------- ### Bulk Insert Documents from JSON File Source: https://github.com/litedb-org/litedb/wiki/Shell Imports multiple documents into a collection from a JSON file. The JSON file must contain an array of documents. ```shell db.customer.bulk my-documents.json ``` -------------------------------- ### Upgrade Datafile via Command-Line Shell Source: https://github.com/litedb-org/litedb/wiki/Update-Datafile The LiteDB shell provides a command to upgrade your v2 datafiles. If the datafile is password protected, include the password in the command. ```shell > upgrade my-old-file.db ``` ```shell > upgrade filename=my-old-file.db;password=mypass ``` -------------------------------- ### Open In-Memory LiteDatabase Source: https://context7.com/litedb-org/litedb/llms.txt Opens an in-memory LiteDB database, which is useful for testing. Always wrap in a 'using' block. ```csharp // In-memory database (great for tests) using var db = new LiteDatabase(new MemoryStream()); ``` -------------------------------- ### Programmatic Connection String Configuration Source: https://context7.com/litedb-org/litedb/llms.txt Configures LiteDB connection options programmatically using a ConnectionString object, equivalent to using a connection string. Always wrap in a 'using' block. ```csharp // Programmatic equivalent var cs = new ConnectionString { Filename = "app.db", Password = "s3cr3t", Connection = ConnectionType.Shared, InitialSize = 10 * 1024 * 1024, Upgrade = true }; using var db2 = new LiteDatabase(cs); ``` -------------------------------- ### Open LiteDatabase with Custom BsonMapper Source: https://context7.com/litedb-org/litedb/llms.txt Opens a LiteDB database with a custom BsonMapper, allowing for configuration like camel case serialization. Always wrap in a 'using' block. ```csharp // With a custom BsonMapper var mapper = new BsonMapper(); mapper.UseCamelCase(); using var db = new LiteDatabase("MyData.db", mapper); ``` -------------------------------- ### Configure LiteDB Connection String in App.config Source: https://github.com/litedb-org/litedb/wiki/Connection-String This XML snippet shows how to define the LiteDB connection string within the App.config file. ```XML ``` -------------------------------- ### Evaluate Arithmetic Expression Source: https://github.com/litedb-org/litedb/wiki/Expressions Shows how to evaluate a complex arithmetic expression directly in the shell. This can be used for calculations or data transformations. ```Shell db.dummy.select ((2 + 11 % 7)-2)/3 ``` -------------------------------- ### Fluent Mapping and Cross-Document References in LiteDB Source: https://github.com/litedb-org/litedb/blob/master/README.md Illustrates how to use LiteDB's fluent mapper for complex data models, including DbRef for cross-document references and embedded sub-documents. This approach is useful for managing relationships between different collections. ```csharp // DbRef to cross references public class Order { public ObjectId Id { get; set; } public DateTime OrderDate { get; set; } public Address ShippingAddress { get; set; } // Embedded sub-document public Customer Customer { get; set; } // DbRef to Customer collection public List Products { get; set; } // DbRef to Products collection } // Re-use mapper from global instance var mapper = BsonMapper.Global; // "Products" and "Customer" are from other collections (not embedded document) mapper.Entity() .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("orders"); // When query Order, includes 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; // ... } } ``` -------------------------------- ### Find and Query Documents Source: https://context7.com/litedb-org/litedb/llms.txt Retrieves documents using LINQ, BsonExpression strings, or the Query builder, with support for skip, limit, count, and existence checks. ```APIDOC ## Find / Query — `ILiteCollection.Find` and `FindOne` LiteDB supports three query styles: LINQ lambda expressions, `BsonExpression` strings, and the fluent `Query()` builder. All find methods accept optional `skip` and `limit` parameters. ```csharp using var db = new LiteDatabase("app.db"); var col = db.GetCollection("customers"); // Find with LINQ predicate IEnumerable active = col.Find(x => x.IsActive && x.Name.StartsWith("A")); // Find with BsonExpression string IEnumerable results = col.Find("$.IsActive = true", skip: 0, limit: 20); // Find by _id Customer c = col.FindById(new BsonValue(1)); // FindOne (first match or null) Customer first = col.FindOne(x => x.Email == "alice@example.com"); // FindAll IEnumerable all = col.FindAll(); // Count / Exists (no document deserialization – uses index only) int total = col.Count(x => x.IsActive); bool anyActive = col.Exists(x => x.IsActive); long longCount = col.LongCount(); // Min / Max on index BsonValue minId = col.Min(); BsonValue maxId = col.Max(); DateTime oldest = col.Min(x => x.CreatedAt); ``` ``` -------------------------------- ### Ensure Index with Expression Source: https://github.com/litedb-org/litedb/wiki/Expressions Shows how to create a unique index on a collection using a case-insensitive expression. This can improve query performance for case-insensitive searches. ```C# collection.EnsureIndex("Name", true, "LOWER($.Name)") ``` ```C# collection.EnsureIndex(x => x.Name, true, "LOWER($.Name)") ``` -------------------------------- ### Retrieve LiteDB Connection String in C# Source: https://github.com/litedb-org/litedb/wiki/Connection-String This C# code demonstrates how to access the LiteDB connection string defined in the App.config file using ConfigurationManager. ```C# System.Configuration.ConfigurationManager.ConnectionStrings["LiteDB"].ConnectionString ``` -------------------------------- ### All Documents with Order and Limit Source: https://github.com/litedb-org/litedb/wiki/Queries Retrieve all documents from a collection, ordered by a specified index in descending order, and limit the results to the first 100. Useful for fetching the most recent items. ```C# // get last added 100 objects of the collection var results = collection.Find(Query.All(Query.Descending), limit: 100); ``` -------------------------------- ### BsonMapper Configuration Source: https://context7.com/litedb-org/litedb/llms.txt The `BsonMapper` controls serialization conventions. It can be configured globally using `BsonMapper.Global` or per `LiteDatabase` instance for custom type registration, naming conventions, and entity mapping. ```APIDOC ## BsonMapper — Custom Type Registration and Naming `BsonMapper` controls serialization conventions. Use `BsonMapper.Global` to configure globally, or pass a custom instance per `LiteDatabase`. ```csharp // Configure global mapper before opening any database BsonMapper.Global.UseCamelCase(); // "MyProperty" → "myProperty" // or BsonMapper.Global.UseLowerCaseDelimiter('_'); // "MyProperty" → "my_property" BsonMapper.Global.SerializeNullValues = true; BsonMapper.Global.EnumAsInteger = true; BsonMapper.Global.EmptyStringToNull = false; // Register custom type (here: System.Drawing.Color) BsonMapper.Global.RegisterType( serialize: c => c.ToArgb(), deserialize: b => System.Drawing.Color.FromArgb(b.AsInt32)); // Fluent entity configuration (alternative to attributes) BsonMapper.Global.Entity() .Id(o => o.OrderId, autoId: false) .Field(o => o.CustomerId, "cust_id") .Ignore(o => o.TempNote) .DbRef(o => o.Customer, "customers"); // Custom collection name resolver BsonMapper.Global.ResolveCollectionName = t => t.Name.ToLower() + "s"; // Use the custom mapper in a specific database only var mapper = new BsonMapper(); mapper.UseCamelCase(); using var db = new LiteDatabase("app.db", mapper); ``` ``` -------------------------------- ### GroupBy with Having Clause Source: https://context7.com/litedb-org/litedb/llms.txt Illustrates grouping documents by a field and filtering these groups using the Having clause with a BsonExpression. Converts results to BsonDocument. ```csharp // GroupBy with Having (BsonExpression) var grouped = col.Query() .GroupBy("$.IsActive") .Having("COUNT(*._id) > 5") .Select("{ active: $.IsActive, total: COUNT(*._id) }") .ToDocuments() .ToList(); ``` -------------------------------- ### Query Documents with Expression Source: https://github.com/litedb-org/litedb/wiki/Expressions Illustrates querying documents in a collection using an expression to filter results. This performs a full scan search and is useful for complex filtering criteria. ```C# Query.EQ("SUBSTRING($.Name, 0, 1)", "T") ``` -------------------------------- ### Conditional Expression with IIF Source: https://github.com/litedb-org/litedb/wiki/Expressions Demonstrates using the `IIF` function within a `select` statement to conditionally format a field based on a document's property. This allows for dynamic data shaping. ```Shell db.customers.select { info: IIF($._id < 20, 'Less', 'Greater') + ' than twenty' } ``` -------------------------------- ### Combined Index and LINQ Filtering Source: https://github.com/litedb-org/litedb/wiki/Queries Demonstrates a query that first filters documents using LiteDB's index-based query (Query.EQ) and then applies further filtering and transformation using LINQ to Objects. This allows for complex post-processing. ```C# col.EnsureIndex(x => x.Name); var result = col .Find(Query.EQ("Name", "John Doe")) // This filter is executed in LiteDB using index .Where(x => x.CreationDate >= x.DueDate.AddDays(-5)) // This filter is executed by LINQ to Object .OrderBy(x => x.Age) .Select(x => new { FullName = x.FirstName + " " + x.LastName, DueDays = x.DueDate - x.CreationDate }); // Transform ``` -------------------------------- ### Map DbRef using BsonRef Attribute Source: https://github.com/litedb-org/litedb/wiki/DbRef Maps the Customer property in the Order class to the 'customers' collection using the [BsonRef] attribute. ```csharp public class Order { public int OrderId { get; set; } [BsonRef("customers")] // where "customers" are Customer collection name public Customer Customer { get; set; } } ``` -------------------------------- ### BsonMapper: Configure Global Naming Convention Source: https://context7.com/litedb-org/litedb/llms.txt Configures the global BSON mapper to use camel case or a custom delimiter for property names during serialization. ```csharp // Configure global mapper before opening any database BsonMapper.Global.UseCamelCase(); // "MyProperty" → "myProperty" // or BsonMapper.Global.UseLowerCaseDelimiter('_'); // "MyProperty" → "my_property" ``` -------------------------------- ### Combined Equality Queries Source: https://github.com/litedb-org/litedb/wiki/Queries Combine multiple equality queries using Query.And to find documents that match all specified criteria. This is efficient when all fields are indexed. ```C# var results = col.Find(Query.And( Query.EQ("FirstName", "John"), Query.EQ("LastName", "Doe") )); ``` -------------------------------- ### Upload File to LiteDB Source: https://github.com/litedb-org/litedb/wiki/Shell Uploads a local file to the database. Overrides existing file content if the fileId already exists. ```shell fs.upload my-file picture.jpg ``` ```shell fs.upload $/photos/pic-001 C:\Temp\mypictures\picture-1.jpg ``` -------------------------------- ### Attribute-Based Indexing Source: https://context7.com/litedb-org/litedb/llms.txt Defines indexes directly on the POCO class using attributes like BsonIndex for non-unique and BsonIndex(true) for unique indexes. ```csharp // Attribute-based indexing (declared on the POCO) public class Product { public int Id { get; set; } [BsonIndex] // non-unique index public string Sku { get; set; } [BsonIndex(true)] // unique index (bool overload) public string Barcode { get; set; } } ``` -------------------------------- ### POCO Mapping: Primary Key and Field Renaming Source: https://context7.com/litedb-org/litedb/llms.txt Configures a property as the primary key using [BsonId] and renames a field in the stored document using [BsonField]. ```csharp public class Order { // Mark as primary key; AutoId = false means caller must supply value [BsonId(autoId: false)] public Guid OrderId { get; set; } // Rename field in the stored document [BsonField("cust_id")] public int CustomerId { get; set; } // ... other properties ```