// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Linq; using LiteDB; namespace NoSQL.LiteDB { public class Data { public string Id { get; set; } public int Iv { get; set; } public double Xv { get; set; } public string Sv { get; set; } public override string ToString() { return string.Format("(iv: {0}, xv: {1}, sv: {2})", Iv, Xv, Sv); } } public class Program { private static BsonDocument Serialize(Data o) { BsonDocument res = new BsonDocument(); res.Add("id", o.Id); res.Add("iv", o.Iv); res.Add("xv", o.Xv); res.Add("sv", o.Sv); return res; } private static Data Deserialize(BsonDocument doc) { Data res = new Data(); res.Id = doc["id"].AsString; res.Iv = doc["iv"].AsInt32; res.Xv = doc["xv"].AsDouble; res.Sv = doc["sv"].AsString; return res; } private static void Dump(ILiteCollection col, BsonExpression expr) { Console.WriteLine("dumping " + expr.Source); bool foundsome = false; foreach (BsonDocument d in col.Find(expr)) { //Console.WriteLine(JsonSerializer.Serialize(d)); Data o = Deserialize(d); Console.WriteLine(o); foundsome = true; } if (!foundsome) { Console.WriteLine("Not found"); } } private const int NREC = 1000; public static void Main(string[] args) { // open ILiteDatabase db = new LiteDatabase(@"C:\Work\L\TestDB.LiD"); ILiteCollection col = db.GetCollection("data"); // put data for(int i = 0; i < NREC; i++) { Data ox = new Data { Id = "Doc#" + (1000 + i + 1), Iv = i + 1, Xv = i + 1.0, Sv = string.Format("This is value {0}", i + 1) }; col.Insert(Serialize(ox)); } // BsonExpression expr; expr = Query.EQ("id", "Doc#" + 1077); // get Dump(col, expr); // delete col.DeleteMany(expr); // get non-existing Dump(col, expr); // update and get expr = Query.EQ("id", "Doc#" + 1088); Dump(col, expr); BsonDocument d = col.FindOne(expr); Data o = Deserialize(d); o.Iv = o.Iv + 1; o.Xv = o.Xv + 0.1; o.Sv = o.Sv + " updated"; col.Update(d["_id"], Serialize(o)); Dump(col, expr); // list all int n = 0; foreach (BsonDocument itd in col.FindAll()) { Data ito = Deserialize(itd); if (!ito.Id.StartsWith("Doc#")) { Console.WriteLine("Unexpected document id: " + ito.Id); } if (ito.Iv < 1 || NREC < ito.Iv) { Console.WriteLine("Unexpected value :" + ito); } n++; } Console.WriteLine(n); // list documents where "Doc#1075" <= id < "Doc#1085" int n2 = 0; expr = Query.And(Query.GTE("id", "Doc#" + 1075), Query.LT("id", "Doc#" + 1085)); foreach (BsonDocument it2d in col.Find(expr)) { Data it2o = Deserialize(it2d); if (!it2o.Id.StartsWith("Doc#")) { Console.WriteLine("Unexpected document id: " + it2o.Id); } n2++; } Console.WriteLine(n2); // close db.Dispose(); Console.ReadKey(); } } }