// 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.Collections.Generic; using System.Linq; using LiteDB; namespace NoSQL.LiteDB { public class Program { private static void Dump(ILiteCollection col, BsonExpression expr) { Console.WriteLine("dumping " + expr); foreach (BsonDocument d in col.Find(expr)) { Console.WriteLine(JsonSerializer.Serialize(d)); /* Console.WriteLine("Id : {0}", d["id"].AsInt32); Console.WriteLine("Customer : {0}", d["customer"].AsString); foreach (BsonDocument d1 in d["items"].AsArray) { Console.WriteLine(" {0,2} {1,-30} {2,10:F2} {3,4} {4,10:F2}", d1["no"].AsInt32, d1["name"].AsString, d1["price"].AsString, d1.ContainsKey("quantity") ? d1["quantity"].AsInt32 : 1, d1.ContainsKey("note") ? d1["note"].AsString : ""); } */ } } public static void Main(string[] args) { // open ILiteDatabase db = new LiteDatabase(@"C:\Work\L\TestDB.LiD"); ILiteCollection col = db.GetCollection("json"); // setup string s1 = "{ \"id\": 1, \"customer\": \"A A\", \"items\": [ { \"no\": 1, \"name\": \"A good C# book\", \"price\": \"19.95\" } ] }"; Console.WriteLine(s1); BsonDocument d1 = JsonSerializer.Deserialize(s1).AsDocument; col.Insert(d1); String s2 = "{ \"id\": 2, \"customer\": \"B B\", \"items\": [ { \"no\": 1, \"name\": \"ASUS MB\", \"price\": \"249.00\" }, " + "{ \"no\": 1, \"name\": \"i5 CPU\", \"price\": \"299.00\", \"note\": \"handle with care\" }, " + "{ \"no\": 1, \"name\": \"4 GB kit\", \"price\": \"249.00\", \"quantity\": 4} ] }"; Console.WriteLine(s2); BsonDocument d2 = JsonSerializer.Deserialize(s2).AsDocument; col.Insert(d2); // query BsonExpression expr; expr = Query.GTE("id", 0); // all (where id >= 0) Dump(col, expr); expr = Query.EQ("id", 2); // where id=2 Dump(col, expr); expr = Query.EQ("customer", "A A"); // where customer='A A' Dump(col, expr); expr = Query.StartsWith("customer", "A"); // where customer LIKE 'A%' Dump(col, expr); // **** I can't get it working **** // where items.name='i5 CPU' // **** I can't get it working **** // where items.name like '%C#%' expr = Query.In("id", new BsonArray(new List { 1, 2 })); // where id IN (1,2) Dump(col, expr); // close db.Dispose(); } } }