Skip to content
Mauricio David edited this page Mar 15, 2015 · 18 revisions

Documents are stored and organized in collections. LiteCollecition is a generic class to manager collections in LiteDB. Each collection must have a unique name:

  • Contains only letters, numbers and _
  • Collection name are case insensitive
  • Collection name starting with _ are reserved for internal use

LiteDB support up to 256 collections per database. Collections are auto created on first Insert or EnsureIndex operation. Run a query, delete or update a document in a non existing collection do not create one.

LiteCollection is a generic class that can be used with <T> as BsonDocument for schemaless documents or a strong typed class. This setting force some paramters to be typed (like Insert or Find). Behind the scene, LiteDB converts your strong type class to generic BsonDocument and all operation use the this generic document.

In this example, both codes produce the same results.

// Strong Type Class
using(var db = new LiteDatabase("mydb.db"))
{
    // Get collection instance
    var col = db.GetCollection<Customer>("customer");
    
    // Insert document to collection - if collection do not exits, 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");
}

// Generic BsonDocument
using(var db = new LiteDatabase("mydb.db"))
{
    // Get collection instance
    var col = db.GetCollection("customer");
    
    // Insert document to collection - if collection do not exits, 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"));
}

This methods are in LiteDatabase instance:

  • GetCollection<T> - This method returns a new instance of LiteCollection. If <T> if ommited, <T> is BsonDocument. This is the only way to get a collection instance.
  • RenameCollection - Rename a collection name only - do not change any document
  • CollectionExists - Check if a collection already exits in database
  • GetCollectionNames - Get all collections names in database
  • DropCollection - Delete all documents, all indexes and the collection reference on database

LiteCollection API

This methods are in LiteCollection instance:

  • Insert - Insert a new document or an IEnumberable of documents. If your document has no _id field, create a new one using ObjectId. If you have a mapped object can be used AutoId. See Object Mapping
  • InsertBulk - Used for insert a high volume of documents. Break documents in batchs and control transaction per batch. Keeps low use of memory cleaning cache after each batch inserted.
  • Update - Update one document identified by _id field. If not found, returns false
  • Delete - Delete document by _id or by a Query result. If not found, returns false
  • Find - Find documents using LiteDB queries. See Query
  • EnsureIndex - Create a new index in a field. See Indexes
  • DropIndex - Drop an existing index

Using DbRef<T>

LiteDB is a document database, so there is no JOIN between collections. If you need reference a document in another document you can use DbRef<T>. This document reference can be loaded during query run or later.

public class Customer
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
}

public class Order
{
    [BsonId]
    public int OrderNumber { get; set; }
    public DateTime OrderDate { get; set; }
    public DbRef<Customer> Customer { get; set; }
}

// Getting customer and order collections
var customers = db.GetCollection<Customer>("customers");
var orders = db.GetCollection<Order>("orders");

// Creating a new Customer instance
var customer = new Customer { CustomerId = 5, Name = "John Doe" };

customers.Insert(customer);

// Create a instance of Order and reference to Customer John
var order = new Order
{
    OrderNumber = 1,
    OrderDate = DateTime.Now,
    Customer = new DbRef<Customer>(customers, customer.CustomerId)
};

orders.Insert(order);

At this point you have a Order document like this:

{
    _id: 1,
    OrderDate: { $date: "2015-01-01T00:00:00Z" },
    Customer: { $ref: "customers", $id: 5 }
}

To query Order and returns Customer information use Include method

// Include Customer document during query process
var order = orders
    .Include((c) => c.Customer.Fetch(db))
    .Find(o => o.OrderDate == DateTime.Now);
    
var john = order.Customer.Item.CustomerName;

// Or include later...

var john = order.Customer.Fetch(db).CustomerName