// 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 MongoDB.Driver; using MongoDB.Bson; namespace NoSQL.MongoDB { public class Program { private static void Dump(IMongoCollection col, BsonDocument criteria) { Console.WriteLine("dumping " + criteria.ToJson()); foreach (BsonDocument d in col.Find(criteria).ToEnumerable()) { Console.WriteLine(d.ToJson()); /* Console.WriteLine("Id : {0}", d.GetValue("id").AsInt32); Console.WriteLine("Customer : {0}", d.GetValue("customer").AsString); foreach (BsonDocument d2 in d.GetValue("items").AsBsonArray) { Console.WriteLine(" {0,2} {1,-30} {2,10:F2} {3,4} {4}", d2.GetValue("no").AsInt32, d2.GetValue("name").AsString, d2.GetValue("price").AsString, d2.GetValue("quantity", 1).AsInt32, d2.GetValue("note", "").AsString); } */ } } public static void Main(string[] args) { // open MongoClient client = new MongoClient("mongodb://localhost:27017"); IMongoDatabase db = client.GetDatabase("TestDB"); IMongoCollection col = db.GetCollection("dn_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 = BsonDocument.Parse(s1); col.InsertOne(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 = BsonDocument.Parse(s2); col.InsertOne(d2); // query Dump(col, BsonDocument.Parse("{ }")); // all Dump(col, BsonDocument.Parse("{ \"id\": 2 }")); // where id=2 Dump(col, BsonDocument.Parse("{ \"customer\": \"A A\" }")); // where customer='A A' Dump(col, BsonDocument.Parse("{ \"customer\": { \"$regex\": \"A.*\"} }")); // where customer like 'A%' Dump(col, BsonDocument.Parse("{ \"items.name\": \"i5 CPU\" }")); // where items.name='i5 CPU' Dump(col, BsonDocument.Parse("{ \"items.name\": { \"$regex\": \".*C#.*\" } }")); // where items.name like '%C#%' Dump(col, BsonDocument.Parse("{ \"id\": { \"$in\": [ 1, 2 ] } }")); // where id in (1,2) Dump(col, BsonDocument.Parse("{ \"items.note\": { \"$exists\": true } }")); // where exists items.note } } }