Skip to content
Dhruv Vemula edited this page Dec 7, 2015 · 18 revisions

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

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

LiteDB supports up to 256 collections per database.

Collections are auto created on first Insert or EnsureIndex operation. Running a query, delete or update on a document in a non existing collection does not create one.

LiteCollection<T> is a generic class that can be used with <T> as BsonDocument for schema-less documents. Internally LiteDB converts T to BsonDocument and all operations use the this generic document.

In this example, both code snippets 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"));
}

LiteDatabase API Instance Methods

  • 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 Instance Methods

  • Insert - Inserts a new document or an IEnumberable of documents. If your document has no _id field, Insert will create a new one using ObjectId. If you have a mapped object, AutoId can be used. See Object Mapping
  • InsertBulk - Used for inserting a high volume of documents. Breaks documents into batches and controls transaction per batch. This method keeps memory usage low by cleaning the acache 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 when a query is run, or after.

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