API examples. Lite DB
Emil Rainero edited this page Apr 27, 2017
·
3 revisions
Call new LiteDatabase() to create a database. It's ok if database already exists. It will just open it.
using LiteDB;
...
LiteDatabase db = new LiteDatabase(@"testing.db");
public class CustomerDataLdb
{
[BsonId] // the unique identifier
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public Dictionary<string, string> Properties { get; set; }
}
LiteCollection<CustomerDataLdb> _customers;
string collectionName = "customers";
if (db.CollectionExists(collectionName)) // can check if collection already exists
db.DropCollection(collectionName);
// create new collection or get it if it already exists
_customers = db.GetCollection<CustomerDataLdb>(collectionName);
if (db.CollectionExists("customers")) {
Debug.Log("It exists!");
}
db.DropCollection("customers");
foreach (string collectionName in db.GetCollectionNames())
{
Debug.Log(collectionName);
}
var customer = new CustomerDataLdb() {
Username = "username",
Password = "password",
Email = "email.address@gmail.com"
};
_customers.Insert(customer);
var entry = _customers.FindOne(a => a.Username == "username");
if (entry != null)
Debug.Log("Found " + entry.Username + " " + entry.Email);
_customers.Delete("username"); // matches against the [BsonId] field Username
entry = _customers.FindOne(a => a.Username == "username");
if (entry != null)
{
entry.Password = "secret";
_customers.Update(entry);
}
Debug.Log("Customers: " + _customers.Count());
foreach (CustomerDataLdb customer in _customers.FindAll())
{
Debug.Log(customer.Username);
}
Hope this helps.