### Path Navigation Examples
Source: http://www.litedb.org/docs/expressions
Demonstrates various ways to navigate through document structures and arrays using path expressions.
```plaintext
$.Price
```
```plaintext
$.Price + 100
```
```plaintext
SUM($.Items[*].Price)
```
```plaintext
$.Address.Street
```
```plaintext
Address.Street
```
```plaintext
123
```
```plaintext
123.45
```
```plaintext
'Hello World'
```
```plaintext
null
```
```plaintext
true
```
```plaintext
false
```
```plaintext
{ key1: 'value1', key2: $.expression }
```
```plaintext
[1, 'string', $.expression]
```
```plaintext
LOWER($.Name)
```
```plaintext
"$.Name"
```
```plaintext
"$.Name.First"
```
```plaintext
"$.Books"
```
```plaintext
"$.Books[0]"
```
```plaintext
"$.Books[*].Title"
```
```plaintext
"$.Books[-1]"
```
```plaintext
"$.Books[@.Title = 'John Doe']"
```
```plaintext
"$.Books[@.Price > 100].Title"
```
```plaintext
"$.Books[SUBSTRING(LOWER(@.Title), 0, 1) = 't']"
```
--------------------------------
### App.config Connection String Example
Source: http://www.litedb.org/docs/connection-string
This example shows how to define a LiteDB connection string within an App.config file, including the filename and password.
```xml
```
--------------------------------
### FileStorage Initialization and Usage
Source: http://www.litedb.org/docs/filestorage
Demonstrates how to get a FileStorage instance, either with default collections or custom names, and perform basic file operations like uploading and finding files.
```csharp
// Gets a FileStorage with the default collections
var fs = db.FileStorage;
// Gets a FileStorage with custom collection name
var fs = db.GetStorage("myFiles", "myChunks");
// Upload a file from file system
fs.Upload("$/photos/2014/picture-01.jpg", @"C:\\Temp\\picture-01.jpg");
// Upload a file from a Stream
fs.Upload("$/photos/2014/picture-01.jpg", "picture-01.jpg", stream);
// Find file reference only - returns null if not found
LiteFileInfo file = fs.FindById("$/photos/2014/picture-01.jpg");
// Now, load binary data and save to file system
file.SaveAs(@"C:\\Temp\\new-picture.jpg");
// Or get binary data as Stream and copy to another Stream
file.CopyTo(Response.OutputStream);
// Find all files references in a "directory"
var files = fs.Find("$/photos/2014/");
```
--------------------------------
### Date Function Examples
Source: http://www.litedb.org/docs/expressions
Examples of functions for manipulating and extracting information from date values.
```plaintext
YEAR(date)
```
```plaintext
DATEADD('year', 3, date)
```
```plaintext
DATEDIFF('day', dateStart, dateEnd)
```
--------------------------------
### DataType Function Examples
Source: http://www.litedb.org/docs/expressions
Examples of functions used for explicit data type conversions.
```plaintext
STRING(expr)
```
```plaintext
INT32(expr)
```
```plaintext
DATETIME(expr)
```
--------------------------------
### Store and Query Documents with LiteDB
Source: http://www.litedb.org/docs/getting-started
Demonstrates basic CRUD operations, indexing, and LINQ-based querying for documents in LiteDB. Ensure the LiteDB DLL is referenced or installed via NuGet.
```csharp
// 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 = "Jane Doe";
col.Update(customer);
// 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("J"))
.OrderBy(x => x.Name)
.Select(x => new { x.Name, NameUpper = x.Name.ToUpper() })
.Limit(10)
.ToList();
// Let's create an index in phone numbers (using expression). It's a multikey index
col.EnsureIndex(x => x.Phones);
// and now we can query phones
var r = col.FindOne(x => x.Phones.Contains("8888-5555"));
}
```
--------------------------------
### Example LiteDB Document Structure
Source: http://www.litedb.org/docs/data-structure
Illustrates a typical document structure in LiteDB, showcasing nested documents, arrays, and various data types.
```json
{
_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"]
}
```
--------------------------------
### Aggregate Function Examples
Source: http://www.litedb.org/docs/expressions
Examples of aggregate functions that process arrays to return a single value.
```plaintext
COUNT(arr)
```
```plaintext
AVG(arr)
```
```plaintext
LAST(arr)
```
--------------------------------
### Create Index using Expression (Filtered Array)
Source: http://www.litedb.org/docs/indexes
Create an index based on a filtered subset of an array within a document. This example indexes the titles of books where the price is less than 20.
```csharp
collection.EnsureIndex("CheapBooks", "LOWER($.Books[@.Price < 20].Title)")
```
--------------------------------
### Rebuild Database with Collation and Password
Source: http://www.litedb.org/docs/pragmas
Rebuild the database with a specified culture, string comparison mode, and a password for encryption. For example, 'pt-BR/None' uses Brazilian Portuguese culture and case-sensitive comparison, with '1234' as the password.
```sql
rebuild {"collation": "pt-BR/None", "password" : "1234"};
```
--------------------------------
### Define Strongly-Typed Document and Get Collection
Source: http://www.litedb.org/docs/object-mapping
Defines a simple Customer class for strongly-typed document mapping and retrieves a LiteDB collection using this class. Alternatively, a schemeless collection can be obtained where T defaults to BsonDocument.
```csharp
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
```
--------------------------------
### Query Order with Included Customer
Source: http://www.litedb.org/docs/dbref
Demonstrates how to retrieve an Order and automatically load the referenced Customer document using the Include method.
```csharp
var orders = db.GetCollection("orders");
var order1 = orders
.Include(x => x.Customer)
.FindById(1);
```
--------------------------------
### Working with Files using FileStorage
Source: http://www.litedb.org/docs/getting-started
Demonstrates how to use LiteDB's FileStorage to upload and download files. This requires an open LiteDatabase instance.
```csharp
// Get file storage with Int Id
var storage = db.GetStorage();
// Upload a file from file system to database
storage.Upload(123, @"C:\\Temp\\picture-01.jpg");
// And download later
storage.Download(123, @"C:\\Temp\\copy-of-picture-01.jpg");
```
--------------------------------
### Create and Populate a BsonDocument
Source: http://www.litedb.org/docs/bsondocument
Demonstrates how to create a new BsonDocument and populate it with various BSON data types, including nested documents and arrays. The `_id` field is automatically set as the first field.
```csharp
var customer = new BsonDocument();
customer["_id"] = ObjectId.NewObjectId();
customer["Name"] = "John Doe";
customer["CreateDate"] = DateTime.Now;
customer["Phones"] = new BsonArray { "8000-0000", "9000-000" };
customer["IsActive"] = true;
customer["IsAdmin"] = new BsonValue(true);
customer["Address"] = new BsonDocument
{
["Street"] = "Av. Protasio Alves"
};
customer["Address"]["Number"] = "1331";
```
--------------------------------
### Define Customer and Order Classes
Source: http://www.litedb.org/docs/dbref
Define simple C# classes for Customer and Order to demonstrate database relationships.
```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; }
}
```
--------------------------------
### Create New Document with SELECT
Source: http://www.litedb.org/docs/expressions
Use the SELECT shell command to create a new document structure, transforming data from existing documents.
```csharp
SELECT { upper_titles: ARRAY(UPPER($.Books[*].Title)) } WHERE $.Name LIKE "John%"
```
--------------------------------
### Generate and Use ObjectId
Source: http://www.litedb.org/docs/data-structure
Shows how to generate a new ObjectId, retrieve its creation time, and create an ObjectId from a hex string.
```csharp
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");
```
--------------------------------
### C# Connection String Retrieval
Source: http://www.litedb.org/docs/connection-string
Demonstrates how to retrieve the connection string defined in App.config using C#.
```csharp
System.Configuration.ConfigurationManager.ConnectionStrings["LiteDB"].ConnectionString
```
--------------------------------
### Map List of Products Reference using Fluent API
Source: http://www.litedb.org/docs/dbref
Configure the Products list in the Order class to be mapped as DbRefs to the 'products' collection using the fluent API.
```csharp
BsonMapper.Global.Entity()
.DbRef(x => x.Products, "products");
```
--------------------------------
### Define Product and Order Classes with List Reference
Source: http://www.litedb.org/docs/dbref
Define Product and Order classes where Order contains a list of Products, intended for DbRef mapping.
```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; }
}
```
--------------------------------
### Convert Object to BSON Document and Serialize to JSON
Source: http://www.litedb.org/docs/data-structure
Demonstrates how to map a .NET object to a BSON document using BsonMapper and then serialize it to a JSON string using JsonSerializer.
```csharp
var customer = new Customer { Id = 1, Name = "John Doe" };
var doc = BsonMapper.Global.ToDocument(customer);
var jsonString = JsonSerialize.Serialize(doc);
```
--------------------------------
### Rebuild Database with Default Options
Source: http://www.litedb.org/docs/pragmas
Rebuild the database using default collation and no password. This can also defragment the datafile.
```sql
rebuild;
```
--------------------------------
### Query with Linq and Includes using Repository
Source: http://www.litedb.org/docs/dbref
Utilize Linq syntax with the Include method when using LiteCollection or Repository to retrieve documents with their referenced data automatically loaded.
```csharp
// repository fluent syntax
db.Query()
.Include(x => x.Customer)
.Include(x => x.Products)
.ToList();
```
--------------------------------
### Select All Pragmas
Source: http://www.litedb.org/docs/pragmas
Use this command to retrieve all pragmas currently set for the datafile.
```sql
select pragmas from $database;
```
--------------------------------
### Typed vs. Untyped Collections in LiteDB
Source: http://www.litedb.org/docs/collections
Demonstrates how to use both typed collections with a specific class and untyped collections with `BsonDocument` for managing data in LiteDB. Both approaches achieve similar results for insertion, indexing, and retrieval.
```csharp
// Typed collection
using(var db = new LiteDatabase("mydb.db"))
{
// Get collection instance
var col = db.GetCollection("customer");
// Insert document to collection - if collection does not exist, it is created
col.Insert(new Customer { Id = 1, Name = "John Doe" });
// Create an index over the Field name (if it doesn't exist)
col.EnsureIndex(x => x.Name);
// Now, search for your document
var customer = col.FindOne(x => x.Name == "john doe");
}
```
```csharp
// Untyped collection (T is BsonDocument)
using(var db = new LiteDatabase("mydb.db"))
{
// Get collection instance
var col = db.GetCollection("customer");
// Insert document to collection - if collection does not exist, it is created
col.Insert(new BsonDocument{ ["_id"] = 1, ["Name"] = "John Doe" });
// Create an index over the Field name (if it doesn't exist)
col.EnsureIndex("Name");
// Now, search for your document
var customer = col.FindOne("$.Name = 'john doe'");
}
```
--------------------------------
### FileStorage Methods
Source: http://www.litedb.org/docs/filestorage
Overview of the primary methods available in the FileStorage API for managing files.
```APIDOC
## FileStorage Methods
### Description
Provides methods to interact with the FileStorage collection for uploading, downloading, deleting, and finding files.
### Methods
- **Upload(string fileId, string filePath)**
- Description: Uploads a file from the specified file system path to the database.
- Parameters:
- `fileId` (string) - The unique identifier for the file, can include directory structure.
- `filePath` (string) - The path to the file on the local file system.
- **Upload(string fileId, string filename, Stream stream)
- Description: Uploads a file from a stream to the database.
- Parameters:
- `fileId` (string) - The unique identifier for the file, can include directory structure.
- `filename` (string) - The name of the file.
- `stream` (Stream) - The stream containing the file data.
- **Download(string fileId, Stream stream)
- Description: Downloads a file from the database and copies its content to the provided stream.
- Parameters:
- `fileId` (string) - The unique identifier of the file to download.
- `stream` (Stream) - The stream to which the file content will be copied.
- **Delete(string fileId)
- Description: Deletes a file reference and all its associated data chunks from the database.
- Parameters:
- `fileId` (string) - The unique identifier of the file to delete.
- **FindById(string fileId)
- Description: Finds a file reference by its ID.
- Returns: `LiteFileInfo` object if found, otherwise null.
- Parameters:
- `fileId` (string) - The unique identifier of the file to find.
- **Find(string fileIdOrDirectory)
- Description: Finds file references based on a file ID or a directory path.
- Returns: An enumerable collection of `LiteFileInfo` objects.
- Parameters:
- `fileIdOrDirectory` (string) - The file ID or directory path to search within.
- **SetMetadata(string fileId, object metadata)
- Description: Updates the metadata associated with a stored file. This does not change the file content.
- Parameters:
- `fileId` (string) - The unique identifier of the file whose metadata needs updating.
- `metadata` (object) - An object containing the metadata key-value pairs.
- **OpenRead(string fileId)
- Description: Opens a stream to read the content of a file.
- Returns: A `LiteFileStream` object for reading the file content.
- Parameters:
- `fileId` (string) - The unique identifier of the file to open for reading.
### Example Usage
```csharp
// Gets a FileStorage with the default collections
var fs = db.FileStorage;
// Gets a FileStorage with custom collection name
var fs = db.GetStorage("myFiles", "myChunks");
// Upload a file from file system
fs.Upload("$/photos/2014/picture-01.jpg", @"C:\Temp\picture-01.jpg");
// Upload a file from a Stream
fs.Upload("$/photos/2014/picture-01.jpg", "picture-01.jpg", stream);
// Find file reference only - returns null if not found
LiteFileInfo file = fs.FindById("$/photos/2014/picture-01.jpg");
// Now, load binary data and save to file system
if (file != null) {
file.SaveAs(@"C:\Temp\new-picture.jpg");
}
// Or get binary data as Stream and copy to another Stream
// file.CopyTo(Response.OutputStream);
// Find all files references in a "directory"
var files = fs.Find("$/photos/2014/");
```
```
--------------------------------
### SELECT $ vs SELECT *
Source: http://www.litedb.org/docs/expressions
Illustrates the difference between using '$' and '*' in SELECT statements for retrieving documents or aggregated results.
```plaintext
SELECT $ FROM customers
```
```plaintext
SELECT * FROM customers
```
--------------------------------
### Import Data from JSON file using $file
Source: http://www.litedb.org/docs/collections
Reads the entire content from a JSON file and imports it. This operation uses the `$file` system collection for input.
```sql
SELECT $ FROM $FILE('customers.json')
```
--------------------------------
### Use BsonCtorAttribute for Constructor Mapping
Source: http://www.litedb.org/docs/object-mapping
Demonstrates using the BsonCtorAttribute to specify which constructor LiteDB should use for initializing objects, allowing for read-only properties.
```csharp
public class Customer
{
public ObjectId CustomerId { get; }
public string Name { get; }
public DateTime CreationDate { get; }
public bool IsActive { get; }
public Customer(string name, bool isActive)
{
CustomerId = ObjectId.NewObjectId();
Name = name;
CreationDate = DateTime.Now;
IsActive = true;
}
[BsonCtor]
public Customer(ObjectId _id, string name, DateTime creationDate, bool isActive)
{
CustomerId = _id;
Name = name;
CreationDate = creationDate;
IsActive = isActive;
}
}
var typedCustomerCollection = db.GetCollection("customer");
```
--------------------------------
### Query with Path Syntax for Includes
Source: http://www.litedb.org/docs/dbref
Use path syntax with the Include method to specify nested or array references to be loaded during a query. Supports wildcard for array elements.
```csharp
orders.Include(new string[] { "$.Customer", "$.Products[*]" });
```
--------------------------------
### Import Data from CSV file using $file
Source: http://www.litedb.org/docs/collections
Reads the entire content from a CSV file and imports it. This operation uses the `$file` system collection for input.
```sql
SELECT $ FROM $FILE('customers.csv')
```
--------------------------------
### Query Documents using SQL Syntax
Source: http://www.litedb.org/docs/expressions
Query documents using SQL syntax, selecting specific fields and filtering array elements.
```csharp
SELECT $.Name, $.Phones[@.Type = "Mobile"] FROM customers
```
--------------------------------
### Create Index using Expression (LOWER)
Source: http://www.litedb.org/docs/indexes
Create an index based on the result of an expression, such as converting a string field to lowercase for case-insensitive searches. This requires specifying the expression as a string.
```csharp
collection.EnsureIndex("Name", "LOWER($.Name)")
```
--------------------------------
### Export Collection to JSON using $file
Source: http://www.litedb.org/docs/collections
Dumps the entire content from a specified collection into a JSON file. This operation uses the `$file` system collection for output.
```sql
SELECT $ INTO $FILE('customers.json') FROM Customers
```
--------------------------------
### Create Index using Expression (SUM)
Source: http://www.litedb.org/docs/indexes
Index the sum of values from an array of objects within a document. This allows for efficient querying based on aggregated values, like the total price of items.
```csharp
collection.EnsureIndex("Total", "SUM($.Items[*].Price)")
```
--------------------------------
### Check BSON Value Data Type and Retrieve as String
Source: http://www.litedb.org/docs/bsondocument
Shows how to check if a BsonValue is a string and how to retrieve its string representation using the `AsString` property. Missing fields in a BsonDocument return `BsonValue.Null`.
```csharp
// Testing BSON value data type
if(customer["Name"].IsString) { ... }
```
```csharp
// Helper to get .NET type
string str = customer["Name"].AsString;
```
--------------------------------
### Custom Type Mapping with BsonMapper
Source: http://www.litedb.org/docs/getting-started
Shows how to register a custom serializer for types like DateTimeOffset to control how they are mapped to BSON documents. This is useful when default serialization is not suitable.
```csharp
BsonMapper.Global.RegisterType
(
serialize: obj =>
{
var doc = new BsonDocument();
doc["DateTime"] = obj.DateTime.Ticks;
doc["Offset"] = obj.Offset.Ticks;
return doc;
},
deserialize: doc => new DateTimeOffset(doc["DateTime"].AsInt64, new TimeSpan(doc["Offset"].AsInt64))
);
```
--------------------------------
### Update Documents using SQL Syntax
Source: http://www.litedb.org/docs/expressions
Update documents using a SQL-like syntax, applying a function to modify the 'Name' field for specific records.
```csharp
UPDATE customers SET Name = LOWER($.Name) WHERE _id = 1
```
--------------------------------
### Set UTC_DATE Pragma
Source: http://www.litedb.org/docs/pragmas
Enable or disable the UTC_DATE pragma. When false, dates are converted to local time on retrieval. Storage is always in UTC.
```sql
pragma UTC_DATE = true;
```
--------------------------------
### Create Index on Embedded Document
Source: http://www.litedb.org/docs/indexes
Create an index on an entire embedded document. This will index all fields within that document, allowing for queries that match on any of its properties.
```csharp
customers.EnsureIndex("Address")
```
--------------------------------
### Export Collection to CSV using $file
Source: http://www.litedb.org/docs/collections
Dumps the entire content from a specified collection into a CSV file. The schema of the first document determines the CSV header. This operation uses the `$file` system collection for output.
```sql
SELECT $ INTO $FILE('customers.csv') FROM Customers
```
--------------------------------
### Map Customer Reference using BsonRef Attribute
Source: http://www.litedb.org/docs/dbref
Use the [BsonRef] attribute to specify that the Customer property in the Order class should be stored as a reference to the 'customers' collection.
```csharp
public class Order
{
public int OrderId { get; set; }
[BsonRef("customers")] // where "customers" is the collection to be referenced
public Customer Customer { get; set; }
}
```
--------------------------------
### Query Documents by Expression
Source: http://www.litedb.org/docs/expressions
Perform a full scan search using a BsonExpression to filter documents based on a substring of the 'Name' field.
```csharp
collection.Find("SUBSTRING($.Name, 0, 1) = 'T'")
```
--------------------------------
### Register Custom Type Mapping for Uri
Source: http://www.litedb.org/docs/object-mapping
Shows how to register a custom mapping for the Uri type using BsonMapper.Global.RegisterType, providing serialize and deserialize functions.
```csharp
BsonMapper.Global.RegisterType
(
serialize: (uri) => uri.AbsoluteUri,
deserialize: (bson) => new Uri(bson.AsString)
);
```
--------------------------------
### Rebuild with en-GB case-insensitive collation
Source: http://www.litedb.org/docs/collation
Rebuilds the datafile using the 'en-GB' culture and case-insensitive string comparison.
```json
rebuild {"collation": "en-GB/IgnoreCase"};
```
--------------------------------
### Map Customer Reference using Fluent API
Source: http://www.litedb.org/docs/dbref
Configure the Customer reference in the Order class using LiteDB's fluent API mapper. Ensure the referenced entity (Customer) has a [BsonId] defined.
```csharp
BsonMapper.Global.Entity()
.DbRef(x => x.Customer, "customers"); // where "customers" are Customer collection name
```
--------------------------------
### Order Stored with DbRef
Source: http://www.litedb.org/docs/dbref
Shows the resulting BSON document structure when an Order is saved with a DbRef to a Customer, storing only the reference ID and collection name.
```json
Order => { _id: 123, Customer: { $id: 4, $ref: "customers"} }
```
--------------------------------
### Create Index on Array Field
Source: http://www.litedb.org/docs/indexes
When indexing an array field, all values within the array are included in the index, allowing searches for any individual value. This is demonstrated with a `Phones` array in the `Customer` class.
```csharp
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string[] Phones { get; set; }
}
var customers = db.GetCollection("customers");
customers.Insert(new Customer { Name = "John", Phones = new string[] { "1", "2", "5" } });
customers.Insert(new Customer { Name = "Doe", Phones = new string[] { "1", "8" } });
customers.EnsureIndex(x => x.Phones);
var result = customers.Find(x => x.Phones.Contains("1")); // returns both documents
```
--------------------------------
### Order with Embedded Customer Document
Source: http://www.litedb.org/docs/dbref
Illustrates how an Order object is stored as an embedded document when no explicit reference mapping is defined.
```json
Order => { _id: 123, Customer: { CustomerId: 99, Name: "John Doe" } }
```
--------------------------------
### Set USER_VERSION Pragma
Source: http://www.litedb.org/docs/pragmas
Modify the USER_VERSION pragma to reserve for user version control. This does not affect datafile behavior.
```sql
pragma USER_VERSION = 1;
```
--------------------------------
### Rebuild with en-US collation
Source: http://www.litedb.org/docs/collation
Rebuilds the datafile using the 'en-US' culture and standard string comparison (case-sensitive).
```json
rebuild {"collation": "en-US/None"};
```
--------------------------------
### Configure BsonMapper for Property Name Delimiter
Source: http://www.litedb.org/docs/object-mapping
Sets a custom delimiter for property names when mapping objects to BSON documents. Ensure the Customer class has properties that align with the expected document fields.
```csharp
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;
```
--------------------------------
### Create Index on Field using Lambda
Source: http://www.litedb.org/docs/indexes
Define an index field using a lambda expression for strongly-typed collections. This provides compile-time checking and improves code readability.
```csharp
EnsureIndex(x => x.Name)
```
--------------------------------
### Ensure Index with BsonExpression
Source: http://www.litedb.org/docs/expressions
Use a BsonExpression string to define a case-insensitive index on a document field.
```csharp
collection.EnsureIndex("idx_name", "LOWER($.Name)", false)
```
--------------------------------
### Rebuild with pt-BR case-insensitive and symbol-ignoring collation
Source: http://www.litedb.org/docs/collation
Rebuilds the datafile using the 'pt-BR' culture, ignoring case and symbols (like punctuation and whitespace).
```json
rebuild {"collation": "pt-BR/IgnoreCase,IgnoreSymbols"};
```
--------------------------------
### Ensure Index with Lambda Expression
Source: http://www.litedb.org/docs/expressions
Alternatively, ensure an index using a lambda expression which LiteDB converts to a BsonExpression.
```csharp
collection.EnsureIndex(x => x.Name.ToLower())
```
--------------------------------
### Create Index on Embedded Document Field
Source: http://www.litedb.org/docs/indexes
Use dotted notation to create an index on a field within an embedded document. This is useful for querying specific properties nested within documents.
```csharp
customers.EnsureIndex("Address.Street")
```
--------------------------------
### File Storage Metadata Structure
Source: http://www.litedb.org/docs/filestorage
This JSON object represents the structure of a file reference and metadata stored in the `_files` collection.
```json
{
_id: "my-photo",
filename: "my-photo.jpg",
mimeType: "image/jpg",
length: { $numberLong: "2340000" },
chunks: 9,
uploadDate: { $date: "2020-01-01T00:00:00Z" },
metadata: { "key1": "value1", "key2": "value2" }
}
```
--------------------------------
### Fluent API for Custom Entity Mapping
Source: http://www.litedb.org/docs/object-mapping
Defines custom mappings for an entity using a fluent API. This allows specifying the document ID field, ignoring properties, and renaming fields without using attributes on the domain class.
```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
```
--------------------------------
### Map Array Elements
Source: http://www.litedb.org/docs/expressions
Applies an expression to each element of an array, returning a new array with the results. The '@' symbol represents the current element in the loop.
```javascript
MAP([1,2,3] => @*2)
```
```javascript
MAP([{a:1, b:2}, {a:3, b:4}] => @.a)
```
--------------------------------
### File Storage Chunk Structure
Source: http://www.litedb.org/docs/filestorage
This JSON object represents a binary data chunk stored in the `_chunks` collection. Multiple chunks form a complete file.
```json
{
_id: { "f": "my-photo", "n": 0 },
data: { $binary: "VHlwZSAob3Igc ... GUpIGhlcmUuLi4" }
}
{
_id: { "f": "my-photo", "n": 1 },
data: { $binary: "pGaGhlcmUuLi4 ... VHlwZSAob3Igc" }
}
{
...
```
--------------------------------
### Sort Array Elements (with Order)
Source: http://www.litedb.org/docs/expressions
Sorts an array based on an expression, allowing explicit control over the sort order (ascending or descending). Use 'asc' or 1 for ascending, 'desc' or -1 for descending.
```javascript
SORT([3,2,5,1,4] => @, 'desc')
```
```javascript
SORT([{a:1, b:2}, {a:2}] => @.a, -1)
```
--------------------------------
### Sort Array Elements (Ascending)
Source: http://www.litedb.org/docs/expressions
Sorts an array in ascending order based on the result of a provided expression. The '@' symbol represents the current element.
```javascript
SORT([3,2,5,1,4] => @)
```
```javascript
SORT([{a:2}, {a:1, b:2}] => @.a)
```
--------------------------------
### Filter Array Elements
Source: http://www.litedb.org/docs/expressions
Creates a new array containing only elements from the original array for which the provided expression evaluates to true. The '@' symbol represents the current element.
```javascript
FILTER([1,2,3,4,5] => @ > 3)
```
```javascript
FILTER([{a:1, b:2}, {a:2}] => @.b != null)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.