public void ShouldReturnAllDataFromCollection() { //Given Mongo db = new Mongo(string.Format("Server={0}:{1}", "localhost", "27017")); db.Connect(); IMongoCollection collection = db["test"]["folks"]; Document doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } }; Document doc2 = new Document() { { "first_name", "Ralph" }, { "middle_initial", "M" }, { "last_name", "Buckingham" }, { "state", "CA" } }; Document doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } }; collection.Insert(doc1); collection.Insert(doc2); collection.Insert(doc3); var queryProvider = new MongoDbCSharpQuery(); try { //When IEnumerable data = queryProvider.RunQuery("localhost", "test", "27017", "folks"); int numberOfRows = 0; foreach (var row in data) numberOfRows++; //Then Assert.AreEqual(3, numberOfRows); } finally { //Clean Up collection.Delete(doc1); collection.Delete(doc2); collection.Delete(doc3); queryProvider.Dispose(); } }
public void TestDefaults() { Mongo m = new Mongo(); Assert.AreEqual("localhost", m.Host); Assert.AreEqual(27017, m.Port); }
public GridFS(Mongo mongo) { this.mongo = mongo; this.bucketName = DEFAULT_ROOT; chunks = this.mongo[this.bucketName][".chunks"]; files = this.mongo[this.bucketName][".files"]; }
public void Connect() { using (Mongo mongo = new Mongo("Server=10.98.0.241:27017")) { mongo.Connect(); } }
//[Test] public void TestMultiThreadedWrites() { Mongo db = new Mongo(); db.Connect(); IMongoCollection col = db["tests"]["threadinserts"]; List <string> identifiers = new List <string> { "A", "B", "C", "D" }; List <Thread> threads = new List <Thread>(); int iterations = 100; foreach (string identifier in identifiers) { Inserter ins = new Inserter { Iterations = iterations, Identifier = identifier, Collection = col }; ThreadStart ts = new ThreadStart(ins.DoInserts); Thread thread = new Thread(ts); threads.Add(thread); } RunAndWait(threads); try{ Assert.AreEqual(identifiers.Count * iterations, col.Count()); }catch (Exception e) { Assert.Fail(e.Message); } }
/// <summary> /// Create a Nut for a specific application account and in a specific configuration container. /// </summary> /// <param name="account">The application account we are creating the nut for.</param> /// <param name="container">The container we are inserting the nut into (e.g. connectionstrings, endpoints, appconfig, etc).</param> /// <param name="nut">Busta nut.</param> /// <returns>True if the nut was added and false if it already exists, and therefore was not added/updated.</returns> public static bool CreateNut(string account, string container, Nut nut) { bool nutAdded = false; Mongo mongo = new Mongo(); mongo.Connect(); var db = mongo.GetDatabase(WellKnownDb.AppConfiguration); var collection = db.GetCollection(container); var doc = new Document(); doc["account"] = account; doc["name"] = nut.Key; doc["value"] = nut.Value; if (nut.Properties != null) { foreach (var k in nut.Properties.Keys) { doc.Add(k, nut.Properties[k]); } } if (collection.FindOne(doc) == null) { collection.Insert(doc); nutAdded = true; } return nutAdded; }
public GridFS(Mongo mongo, string bucketName) { this.mongo = mongo; this.bucketName = bucketName; chunks = this.mongo[this.bucketName][".chunks"]; files = this.mongo[this.bucketName][".files"]; }
public IList<string> GetCollections(string server, string database, string port) { _db = new Mongo(string.Format("Server={0}:{1}", server, port)); try { _db.Connect(); } catch (SocketException ex) { throw new UnknownServerException(string.Format("Unknown server: {0}:{1}", server, port), ex); } IList<String> collectionNames = _db[database].GetCollectionNames(); var filteredCollections = new List<string>(); var hiddenCollectionCriteria = new string[] {"cubicle", "tmp.", ".$", "system.indexes"}; foreach (string collectionName in collectionNames) { if (!hiddenCollectionCriteria.Any(criteria => collectionName.Contains(criteria))) { int periodIndex = collectionName.IndexOf("."); string collection = collectionName; if (periodIndex >= 0 && periodIndex != (collectionName.Length - 1)) collection = collectionName.Substring(collectionName.IndexOf(".") + 1); filteredCollections.Add(collection); } } return filteredCollections; }
public void ShouldReturnCollectionsFromDatabase() { //Given Mongo db = new Mongo(string.Format("Server={0}:{1}", "localhost", "27017")); db.Connect(); IMongoCollection collection = db["test"]["folks"]; Document doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } }; Document doc2 = new Document() { { "first_name", "Ralph" }, { "middle_initial", "M" }, { "last_name", "Buckingham" }, { "state", "CA" } }; Document doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } }; collection.Insert(doc1); collection.Insert(doc2); collection.Insert(doc3); var queryProvider = new MongoDbCSharpQuery(); try { //When IList<string> collections = queryProvider.GetCollections("localhost", "test", "27017"); //Then Assert.IsNotNull(collections.Where(c => c == "folks").SingleOrDefault()); } finally { //Clean Up collection.Delete(doc1); collection.Delete(doc2); collection.Delete(doc3); queryProvider.Dispose(); } }
public static void Main(string[] args) { SetupDocuments(); Mongo m = new Mongo(); m.Connect(); Database db = m["benchmark"]; db.MetaData.DropDatabase(); Console.WriteLine("Starting Tests"); RunEncodeTest("encode (small)",small); RunEncodeTest("encode (medium)", medium); RunEncodeTest("encode (large)", large); RunDecodeTest("decode (small)",small); RunDecodeTest("decode (medium)", medium); RunDecodeTest("decode (large)", large); db.MetaData.DropDatabase(); RunInsertTest("insert (small, no index)", db, "small_none",small,false,false); RunInsertTest("insert (medium, no index)", db, "medium_none",medium,false,false); RunInsertTest("insert (large, no index)", db, "large_none",large,false,false); RunInsertTest("insert (small, indexed)", db, "small_index",small,true,false); RunInsertTest("insert (medium, indexed)", db, "medium_index",medium,true,false); RunInsertTest("insert (large, indexed)", db, "large_index",large,true,false); RunInsertTest("batch insert (small, no index)", db, "small_bulk",small,false,true); RunInsertTest("batch insert (medium, no index)", db, "medium_bulk",medium,false,true); RunInsertTest("batch insert (large, no index)", db, "large_bulk",large,false,true); Document fonespec = new Document().Append("x",perTrial/2); RunFindTest("find_one (small, no index)", db, "small_none",fonespec,false); RunFindTest("find_one (medium, no index)", db, "medium_none",fonespec,false); RunFindTest("find_one (large, no index)", db, "large_none",fonespec,false); RunFindTest("find_one (small, indexed)", db, "small_index",fonespec,false); RunFindTest("find_one (medium, indexed)", db, "medium_index",fonespec,false); RunFindTest("find_one (large, indexed)", db, "large_index",fonespec,false); RunFindTest("find (small, no index)", db, "small_none",fonespec,true); RunFindTest("find (medium, no index)", db, "medium_none",fonespec,true); RunFindTest("find (large, no index)", db, "large_none",fonespec,true); RunFindTest("find (small, indexed)", db, "small_index",fonespec,true); RunFindTest("find (medium, indexed)", db, "medium_index",fonespec,true); RunFindTest("find (large, indexed)", db, "large_index",fonespec,true); Document findRange = new Document().Append("x",new Document().Append("$gt",perTrial/2).Append("$lt", perTrial/2 + batchSize)); RunFindTest("find range (small, indexed)", db, "small_index",findRange,true); RunFindTest("find range (medium, indexed)", db, "medium_index",findRange,true); RunFindTest("find range (large, indexed)", db, "large_index",findRange,true); System.Console.WriteLine("Press any key to continue..."); System.Console.ReadKey(); }
public GridFS(Mongo mongo, Database db, string bucketName) : this() { this.mongo = mongo; this.bucketName = bucketName; chunks = db[this.bucketName + ".chunks"]; files = db[this.bucketName + ".files"]; this.mongo.SetCurrentDB(db); }
public void FavoriteUpdate_Multiple() { string connstr = ConfigurationManager.AppSettings["mongoDBTest"]; var mongo = new Mongo(connstr); mongo.Connect(); var testDB = mongo.GetDatabase("myTest"); UserFavorite fav = new UserFavorite(testDB, "lynn"); fav.Update("q", 1, "t1,t2,t2"); }
public void Initialize() { should_not_already_be_initialized(); lock (_syncRoot) { should_not_already_be_initialized(); _mongo = new Mongo(); _mongo.Connect(); _db = _mongo.getDB("FubuDinner"); _isInitialized = true; } }
public void TestThatConnectMustBeCalled() { Mongo m = new Mongo(); bool thrown = false; try{ Database db = m["admin"]; db["$cmd"].FindOne(new Document().Append("listDatabases", 1.0)); }catch(MongoCommException){ thrown = true; } Assert.IsTrue(thrown, "MongoComException not thrown"); }
public void TestThatConnectMustBeCalled() { Mongo m = new Mongo(); bool thrown = false; try{ Database db = m["admin"]; db["$cmd"].FindOne(new Document().Append("listDatabases", 1.0)); }catch (MongoCommException) { thrown = true; } Assert.IsTrue(thrown, "MongoComException not thrown"); }
public static List<Nut> FindAllInContainer(string account, string container, IDictionary<string,string> properties) { List<Nut> nuts = new List<Nut>(); Mongo mongo = new Mongo(); mongo.Connect(); var db = mongo.GetDatabase(WellKnownDb.AppConfiguration); var collection = db.GetCollection(container); var query = new Document(); query["account"] = account; foreach (string k in properties.Keys) { var t = properties[k]; if (k == "value") { query["value"] = t as string; } else { query[k] = properties[k]; } } var result = collection.Find(query); foreach (var r in result.Documents) { var nut = new Nut { Database = WellKnownDb.AppConfiguration, Table = container, Key = r["name"] as string, Properties = new Dictionary<string, string>() }; nut.Value = r["value"] as string; nut.Uri = string.Format("/{0}/{1}/{2}", account, container, r["name"]); foreach (var j in r.Keys) { nut.Properties.Add(j, r[j] as string); } nuts.Add(nut); } return nuts; }
public void TestMultiThreadedReadsAndWrites() { Mongo db = new Mongo(); db.Connect(); IMongoCollection col = db["tests"]["threadreadinserts"]; List <string> identifiers = new List <string> { "A", "B", "C", "D" }; List <string> colnames = new List <string> { "smallreads", "smallreads", "smallreads", "smallreads" }; List <Thread> threads = new List <Thread>(); List <Reader> readers = new List <Reader>(); int writeiterations = 100; int readiterations = 50; foreach (string identifier in identifiers) { Inserter ins = new Inserter { Iterations = writeiterations, Identifier = identifier, Collection = col }; ThreadStart ts = new ThreadStart(ins.DoInserts); Thread thread = new Thread(ts); threads.Add(thread); } foreach (string colname in colnames) { Reader r = new Reader { Iterations = readiterations, Collection = db["tests"][colname] }; readers.Add(r); ThreadStart ts = new ThreadStart(r.DoReads); Thread thread = new Thread(ts); threads.Add(thread); } RunAndWait(threads); try{ Assert.AreEqual(identifiers.Count * writeiterations, col.Count()); }catch (Exception e) { Assert.Fail(e.Message); } foreach (Reader r in readers) { Assert.AreEqual(readiterations, r.Count, "A reader did not read everytime."); } }
public void SetUp() { using(var mongo = new Mongo(CreateConnectionStringBuilder().ToString())) { mongo.Connect(); var testDatabase = mongo[testDatabaseName]; if(testDatabase.MetaData.FindUser(testuser) == null) testDatabase.MetaData.AddUser(testuser, testpass); var adminDatabase = mongo["admin"]; if(adminDatabase.MetaData.FindUser(adminuser) == null) adminDatabase.MetaData.AddUser(adminuser, adminpass); } }
/// <summary> /// Setup the collection and insert some data into it. /// </summary> public void Setup() { string connstr = ConfigurationManager.AppSettings["simple"]; if(String.IsNullOrEmpty(connstr)) throw new ArgumentNullException("Connection string not found."); mongo = new Mongo(connstr); mongo.Connect(); simple = mongo["simple"]; categories = simple["categories"]; Clean(); var names = new string[]{"Bluez", "Jazz", "Classical", "Rock", "Oldies", "Heavy Metal"}; foreach(string name in names){ categories.Insert(new Document(){{"name", name}}); } }
public void TestSetAndGetFunction() { string connstr = ConfigurationManager.AppSettings["mongoDBTest"]; var mongo = new Mongo(connstr); mongo.Connect(); var testDB = mongo.GetDatabase("myTest"); AdminParameters.DB = testDB; AdminParameters.Set(AdminParameters.SuggesttedTagsForUserFavorite, "hello"); Assert.AreEqual(AdminParameters.Get(AdminParameters.SuggesttedTagsForUserFavorite), "hello"); mongo.Disconnect(); }
public IEnumerable RunQuery(string server, string database, string port, string query) { if (database == string.Empty) throw new QueryValidationException("You must specify a non-empty database name"); if (query == string.Empty) throw new QueryValidationException("You must specify a non-empty query"); _db = new Mongo(string.Format("Server={0}:{1}", server, port)); IList<DictionaryBase> documents = new List<DictionaryBase>(); try { _db.Connect(); } catch (SocketException ex) { throw new UnknownServerException(string.Format("Unknown server: {0}:{1}", server, port), ex); } string[] queryParts = query.Split(':'); string collection = queryParts[0]; if (queryParts.Length > 1) { Document spec = new Document(); string where = queryParts[1]; const string LIMIT_TEXT = " limit "; int limitIndex = where.IndexOf(LIMIT_TEXT); int limit = 0; if (limitIndex > -1) { string limitText; if (int.TryParse(where.Substring(limitIndex + LIMIT_TEXT.Length), out limit)) where = where.Substring(0, limitIndex); } spec.Append("$where", new Code(where)); _cursor = _db[database][collection].Find(spec, limit, 0); } else _cursor = _db[database][collection].FindAll(); return _cursor.Documents; //Document d = db[database].SendCommand("db.test.find();"); }
public void FavoriteAdd() { string connstr = ConfigurationManager.AppSettings["mongoDBTest"]; var mongo = new Mongo(connstr); mongo.Connect(); var testDB = mongo.GetDatabase("myTest"); UserFavorite fav = new UserFavorite(testDB, "testUserName" + DateTime.Now.ToShortTimeString()); fav.Update("question", 101, "tag1,tag2"); fav.Update("question", 102, "tag3,tag4"); fav.Update("question", 104, "tag3,tag4,tag5"); fav.Update("question", 103, "tag1,tag2"); fav.Update("k", 101, "tag1,tag2"); fav.Update("k", 102, "tag2,tag7"); fav.Update("k", 103, "tag1,tag5"); fav.Update("k", 104, "tag1,tag5"); fav.Update("k", 105, "tag1,tag5"); fav.Update("k", 106, "tag1,tag5"); Assert.IsTrue(Compare(fav.GetTags("k"), "tag1,tag2,tag7,tag5")); Assert.IsTrue(Compare(fav.GetTags("question"), "tag1,tag2,tag3,tag4,tag5")); Assert.AreEqual("tag1,tag5", fav.GetTags("k", 103)); Assert.AreEqual("tag1,tag2", fav.GetTags("question", 103)); Assert.IsTrue(fav.GetIDs("question", "tag1").Contains(101)); Assert.IsTrue(fav.GetIDs("question", "tag1").Contains(103)); Assert.AreEqual(5, fav.GetIDs("k", "tag1").Count); Assert.AreEqual(6, fav.GetIDs("k").Count); Assert.AreEqual(0, fav.GetIDs("foofoo").Count); Assert.AreEqual(4, fav.GetIDs("question").Count); Assert.IsTrue(fav.HasFavorite("question", 103)); Assert.IsFalse(fav.HasFavorite("k", 203)); fav.Remove("question", 103); Assert.IsFalse(fav.HasFavorite("question", 103)); mongo.Disconnect(); }
/// <summary> /// The main. /// </summary> /// <param name="args">The args.</param> private static void Main( string[] args ) { // Connect to the mongo instance. var mongo = new Mongo(); mongo.Connect(); // Use the myorders database. Database db = mongo.GetDatabase("myorders"); // Get the orders collection. IMongoCollection orders = db.GetCollection("orders"); DeleteAllDocumentsFromCollection(orders); CreateAndInsertDocumentIntoCollection(orders); QueryFromCollection( orders ); Console.WriteLine("\nPress Enter to Exit."); Console.ReadLine(); }
public void ShouldGetDataFromLocalMongoDbServer() { //Given Mongo db = new Mongo(string.Format("Server={0}:{1}", "localhost", "27017")); db.Connect(); IMongoCollection collection = db["test"]["folks"]; Document doc1 = new Document() { { "first_name", "Bill" }, { "middle_initial", "Q" }, { "last_name", "Jackson" }, { "address", "744 Nottingham St." } }; Document doc2 = new Document() { { "first_name", "Ralph" }, { "middle_initial", "M" }, { "last_name", "Buckingham" }, { "state", "CA" } }; Document doc3 = new Document() { { "first_name", "Ronald" }, { "middle_initial", "Q" }, { "last_name", "Weasly" }, { "city", "Santa Rosa" } }; collection.Insert(doc1); collection.Insert(doc2); collection.Insert(doc3); IMongoQuery query = new MongoDbCSharpQuery(); IMongoQueryFactory factory = new MongoDbCSharpQueryFactory(query); MainViewModel viewModel = new MainViewModel(factory) { Server = "localhost", Database = "test", Port = "27017", Query = "folks:this.middle_initial == 'Q'" }; try { //When viewModel.RunQueryCommand.Execute(null); //Then Assert.AreEqual(2, viewModel.Items.Count); Assert.AreEqual(6, viewModel.Headers.Count); //including _id } finally { //Clean Up collection.Delete(doc1); collection.Delete(doc2); collection.Delete(doc3); } }
protected void CreateMongoDB(String dbName) { //mongod.exe must be running for this to work. var mongo = new Mongo(); mongo.Connect(); //if the database is not found in c:\data\db it will be created. var db = mongo.GetDatabase(dbName); //declare a new "table" var categories = db.GetCollection("categories"); //create a new key value set var document = new Document(); document["Name"] = "Product"; document["Name"] = "Price"; //create the "tabt" categories.Insert(document); mongo.Disconnect(); }
public static void GenerateMongoDB () { var json = new MongoJson(); var mongo = new Mongo(); mongo.Connect(); //Create clean database and collection for Notes var db = mongo["SupermarkertsDB"]; db.SendCommand("dropDatabase"); var products = db["Products"]; List<int> ids; var jsonData = GenerateJSONReports.ExatractJsonData(out ids); foreach (var item in jsonData) { var jsonDocument = json.DocumentFrom(item); products.Insert(jsonDocument); } mongo.Disconnect(); }
//[Test] public void TestMultiThreadedReads() { Mongo db = new Mongo(); db.Connect(); List <string> colnames = new List <string> { "smallreads", "smallreads", "smallreads", "smallreads" }; List <Thread> threads = new List <Thread>(); List <Reader> readers = new List <Reader>(); int iterations = 50; foreach (string colname in colnames) { Reader r = new Reader { Iterations = iterations, Collection = db["tests"][colname] }; readers.Add(r); ThreadStart ts = new ThreadStart(r.DoReads); Thread thread = new Thread(ts); threads.Add(thread); } RunAndWait(threads); try{ //Connection still alive? db["tests"]["smallreads"].Count(); }catch (Exception e) { Assert.Fail(e.Message); } foreach (Reader r in readers) { Assert.AreEqual(iterations, r.Count, "A reader did not read everytime."); } }
protected String GetMongoDBResults(String dbName) { //mongod.exe must be running for this to work. var mongo = new Mongo(); mongo.Connect(); //if the database is not found in c:\data\db it will be created. var db = mongo.GetDatabase(dbName); //declare a new "table" var categories = db.GetCollection("categories"); //get the categories table var category = categories.FindOne(new Document() { { "Name","Price" } }); //alternatively you can get all documents in the database var documents = categories.FindAll().Documents; String res = category["Name"].ToString(); //diconnect mongo.Disconnect(); //return results in a EF friendly shapre just because that's what I'm working with mostly nowadays return res; }
// database private void ConnectToDatabase() { db_server = new MongoDB.Driver.Mongo(_connectionString); db_server.Connect(); MongoDB.Driver.IMongoDatabase db = db_server.GetDatabase("MongoBlog"); collection = db.GetCollection("blogposts"); return; }
public void TestExplicitConnection() { Mongo m = new Mongo(); Assert.IsTrue(m.Connect()); }
public MongoDbWr() { mongo = new Mongo(); mongo.Connect(); }
public GridFS(Mongo mongo, string bucketName) : this(mongo, mongo.CurrentDB == null ? mongo.GetDB("test") : mongo.CurrentDB, bucketName) { }
public GridFS(Mongo mongo, Database db) : this(mongo, db, DEFAULT_ROOT) { }
public GridFS(Mongo mongo) : this(mongo, mongo.CurrentDB == null ? mongo.GetDB("test") : mongo.CurrentDB, DEFAULT_ROOT) { }
public void TestExplicitConnection() { Mongo m = new Mongo(); Assert.IsTrue(m.Connect()); }
public void TestDefaults() { Mongo m = new Mongo(); Assert.AreEqual("localhost", m.Host); Assert.AreEqual(27017, m.Port); }