// 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 MongoDB.Driver; using MongoDB.Bson; namespace NoSQL.MongoDB { 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.GetValue("id").AsString; res.Iv = doc.GetValue("iv").AsInt32; res.Xv = doc.GetValue("xv").AsDouble; res.Sv = doc.GetValue("sv").AsString; return res; } private static void Dump(IMongoCollection col, BsonDocument doc) { Console.WriteLine("dumping " + doc.ToJson()); bool foundsome = false; foreach (BsonDocument d in col.Find(doc).ToEnumerable()) { //Console.WriteLine(d.ToJson()); Data o = Deserialize(d); Console.WriteLine(o); foundsome = true; } if (!foundsome) { Console.WriteLine("Not found"); } } private const int NREC = 1000; private const int DN_OFFSET = 3 * NREC; public static void Main(string[] args) { // open MongoClient client = new MongoClient("mongodb://localhost:27017"); IMongoDatabase db = client.GetDatabase("TestDB"); IMongoCollection col = db.GetCollection("data"); // put data for (int i = 0; i < NREC; i++) { Data onew = new Data { Id = "Doc#" + (DN_OFFSET + i + 1), Iv = i + 1, Xv = i + 1.0, Sv = string.Format("This is value {0}", i + 1) }; col.InsertOne(Serialize(onew)); } BsonDocument doc = new BsonDocument(); doc["id"] = "Doc#" + (DN_OFFSET + 77); // get Dump(col, doc); // delete col.DeleteMany(doc); // get non existing Dump(col, doc); // update and get doc["id"] = "Doc#" + (DN_OFFSET + 88); Dump(col, doc); Data o = Deserialize(col.Find(doc).First()); o.Iv = o.Iv + 1; o.Xv = o.Xv + 0.1; o.Sv = o.Sv + " updated"; col.FindOneAndReplace(doc, Serialize(o)); Dump(col, doc); // list all int n = 0; foreach (BsonDocument itd in col.Find(new BsonDocument()).ToEnumerable()) { 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#n075" <= id < "Doc#n085" int n2 = 0; IDictionary range = new Dictionary(); range.Add("$gte", "Doc#" + (DN_OFFSET + 75)); range.Add("$lt", "Doc#" + (DN_OFFSET + 85)); doc["id"] = new BsonDocument(range); foreach (BsonDocument it2d in col.Find(doc).ToEnumerable()) { Data it2o = Deserialize(it2d); if (!it2o.Id.StartsWith("Doc#")) { Console.WriteLine("Unexpected document id: " + it2o.Id); } n2++; } Console.WriteLine(n2); } } }