public Initializer(MongoDatabase database) { _database = database; if (!_database.CollectionExists(Collections.USERS)) _database.CreateCollection(Collections.USERS); if (!_database.CollectionExists(Collections.TODOS)) _database.CreateCollection(Collections.TODOS); }
public MongoAtHomeDataRepository() { _mongoServer = MongoServer.Create(ApplicationSettings.MongoDBConnectionString); _mongoDatabase = _mongoServer.GetDatabase(_dbName); if (!_mongoDatabase.CollectionExists("clientinformation")) _mongoDatabase.CreateCollection("clientinformation"); if (!_mongoDatabase.CollectionExists("workunit")) _mongoDatabase.CreateCollection("workunit"); }
public void Seed() { // Seed initial data if (!DatabaseMongo.CollectionExists("objects")) { // http://mongodb.github.io/mongo-csharp-driver/2.0/getting_started/quick_tour/ // Seed with object data var collection = DatabaseMongo.GetCollection <BsonDocument>("objects"); string objJson = @"{ 'ObjectId': '12345678', 'FileId':'7ad00d95-f663-4db9-b379-1ff0f30a616d', 'ClassName': 'AcDbLine', 'Color': 'BYLAYER', 'EndPoint': { 'ClassName': 'Point3D', 'X': 294742.67173893179, 'Y': 93743.0034136844, 'Z': 0 }, 'Layer': 'СО_Выноски', 'Length': 150, 'LineWeight': 'LineWeight040', 'Linetype': 'Continuous', 'StartPoint': { 'ClassName': 'Point3D', 'X': 294742.67173893179, 'Y': 93893.0034136844, 'Z': 0 } }"; BsonDocument doc = BsonDocument.Parse(objJson); collection.Insert(doc); } if (!DatabaseMongo.CollectionExists("files")) { var collection = DatabaseMongo.GetCollection <BsonDocument>("files"); string docJson = @"{ 'FileId':'7ad00d95-f663-4db9-b379-1ff0f30a616d', 'Hash':'a4733bbed995e26a389c5489402b3cee', 'Path':'D:\\Documents\\Dropbox\\CrawlDwgs\\084cdbd1-cb5f-4380-a04a-f577d85a7bbb.dwg', 'Scanned':false }"; BsonDocument doc = BsonDocument.Parse(docJson); collection.Insert(doc); } }
void Initialize() { _server = MongoServer.Create(_configuration.Url); _database = _server.GetDatabase(_configuration.DefaultDatabase); if (!_database.CollectionExists(CollectionName)) _database.CreateCollection(CollectionName); _collection = _database.GetCollection(CollectionName); if (!_database.CollectionExists(IncrementalKeysCollectionName)) _database.CreateCollection(IncrementalKeysCollectionName); _incrementalKeysCollection = _database.GetCollection(IncrementalKeysCollectionName); }
public static void performOperation() { MongoClient mc = new MongoClient("mongodb://aks-osx.local:27017,aks-osx.local:27018,aks-osx.local:27019/?readPreference=primaryPreferred"); IList cursorList = new ArrayList(); long counter = 0; MongoServer ms = mc.GetServer(); MongoDatabase mDb = ms.GetDatabase("test"); using (ms.RequestStart(mDb)) { while (true) { ++counter; try { bool collExists = mDb.CollectionExists("data"); var coll = mDb.GetCollection("data"); long collCount = coll.Count(); if (counter % 100 == 0) { Console.WriteLine("Collection Stats [Thread: " + Thread.CurrentThread.ManagedThreadId + ", Exists: " + collExists + ", Count: " + collCount + ", listSize: " + cursorList.Count + "]"); } cursorList.Add(coll.FindAll()); } catch (Exception ex) { Console.WriteLine("Caught Exception within While Loop: " + ex.StackTrace); } } } }
/// <summary> /// Verifies the the MongoDatabase collection exists or creates it if it doesn't. /// </summary> protected void VerifyCollection() { if (!_mongoDatabase.CollectionExists(_collectionName)) { _mongoDatabase.CreateCollection(_collectionName, _collectionCreationOptions); } }
public static void Main(string[] args) { var client = new MongoClient ("mongodb://localhost:27017/todos"); var server = client.GetServer (); db = server.GetDatabase ("todos"); if (db == null) { Console.WriteLine ("Connection failed."); return; } if (!db.CollectionExists ("todos")) { var todoCollection = db.GetCollection ("todos"); // quick order by date todoCollection.CreateIndex ("created"); // enable fulltext search todoCollection.CreateIndex (IndexKeys.Text ("description")); } InsertTodos (); SelectTodos(); UpdateTodos (); Eval (); GridFS (); }
public void setUp() { wammerDb = mongodb.GetDatabase("wammer"); if (wammerDb.CollectionExists("attachments")) { wammerDb.DropCollection("attachments"); } wammerDb.CreateCollection("attachments"); objectId1 = Guid.NewGuid().ToString(); doc = new Attachment { object_id = objectId1, title = "title1", description = "description1" }; AttachmentCollection.Instance.Save(doc); handler = new AttachmentGetHandler(); server = new HttpServer(8080); server.AddHandler("/api/get/", handler); server.Start(); //host = new WebServiceHost(svc, new Uri("http://localhost:8080/api/")); //host.Open(); }
public void Handle(NewBenefitDefinedEvent args) { if (_mongoDataBase.CollectionExists("Benefits") == false) { _mongoDataBase.CreateCollection("Benefits"); } var benefitsCollection = _mongoDataBase.GetCollection <BenefitDto>("Benefits"); var benefit = new BenefitDto { Id = args.BenefitId, BenefitType = args.BenefitType, Description = args.BenefitDescription, HasMaxElectionAmount = args.HasMaxElectionAmount, MaxElectionAmount = args.MaxElectionAmount, PlanId = args.PlanId, CompanyId = args.CompanyId, }; var safeModeResult = benefitsCollection.Save(benefit); if (!safeModeResult.Ok) { //log! //push a message to an admin q? } }
/// <summary> /// 封装对MongoDB 的操作处理。 /// </summary> public MongoDBHelper(bool createNewCollection) { var cfgs = CONNECTION_STRING.Split(':'); if (cfgs.Length != 2) { throw new MB.Util.APPException("请先配置Mongo数据库连接字符窜配置有误.例如:MongoDbConnection=IP:database", Util.APPMessageType.SysErrInfo); } _ConnectionString = string.Format("mongodb://{0}", cfgs[0]); _DataBaseName = cfgs[1]; _Server = MongoServer.Create(_ConnectionString); string collectionName = typeof(T).FullName; //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = _Server.GetDatabase(_DataBaseName) as MongoDatabase; if (createNewCollection) { mongoDatabase.DropCollection(collectionName); } if (mongoDatabase.CollectionExists(collectionName)) { mongoDatabase.CreateCollectionSettings <T>(collectionName); } _DataCollection = mongoDatabase.GetCollection <T>(collectionName); //链接数据库 _Server.Connect(); }
public void BankAccountsCollection(MongoDatabase db) { if (db.CollectionExists("BankAccounts") == false) { db.CreateCollection("BankAccounts"); } }
public MongoQueue(MongoQueConfig config) { // our queue name will be the same as the message class _database = MongoDatabase.Create(config.ConnectionString); if (!_database.CollectionExists(_queueName)) { try { Log.InfoFormat("Creating queue '{0}' size {1}", _queueName, config.QueueSize); var options = CollectionOptions .SetCapped(true) // use a capped collection so space is pre-allocated and re-used .SetAutoIndexId(true) .SetMaxSize(config.QueueSize); // limit the size of the collection and pre-allocated the space to this number of bytes _database.CreateCollection(_queueName, options); var col = _database.GetCollection(_queueName); col.EnsureIndex(new[] { "Dequeued" }); col.EnsureIndex(new[] { "Equeued" }); } catch { // assume that any exceptions are because the collection already exists ... } } // get the queue collection for our messages _queue = _database.GetCollection <MongoMessage <T> >(_queueName); }
/// <summary> /// Create Collection /// </summary> /// <param name="strObjTag"></param> /// <param name="treeNode"></param> /// <param name="collectionName"></param> /// <returns></returns> public static Boolean CreateCollection(String strObjTag, TreeNode treeNode, String collectionName) { //不支持中文 JIRA ticket is created : SERVER-4412 //SERVER-4412已经在2013/03解决了 //collection names are limited to 121 bytes after converting to UTF-8. Boolean rtnResult = false; MongoDatabase mongoDB = GetMongoDBBySvrPath(strObjTag); String strSvrPath = SystemManager.GetTagData(strObjTag); String svrKey = strSvrPath.Split("/".ToCharArray())[(int)PathLv.InstanceLv]; String ConKey = strSvrPath.Split("/".ToCharArray())[(int)PathLv.ConnectionLv]; if (mongoDB != null) { if (!mongoDB.CollectionExists(collectionName)) { mongoDB.CreateCollection(collectionName); foreach (TreeNode item in treeNode.Nodes) { if (item.Tag.ToString().StartsWith(COLLECTION_LIST_TAG)) { item.Nodes.Add(UIHelper.FillCollectionInfoToTreeNode(collectionName, mongoDB, ConKey + "/" + svrKey)); } } rtnResult = true; } } return(rtnResult); }
/// <summary> /// Create Collection /// </summary> /// <param name="strObjTag"></param> /// <param name="treeNode"></param> /// <param name="collectionName"></param> /// <returns></returns> public static Boolean CreateCollection(String strObjTag, TreeNode treeNode, String collectionName) { Boolean rtnResult = false; MongoDatabase mongoDB = GetMongoDBBySvrPath(strObjTag); String strSvrPath = SystemManager.GetTagData(strObjTag); String svrKey = strSvrPath.Split("/".ToCharArray())[(int)PathLv.ServerLV]; String ConKey = strSvrPath.Split("/".ToCharArray())[(int)PathLv.ConnectionLV]; if (mongoDB != null) { if (!mongoDB.CollectionExists(collectionName)) { mongoDB.CreateCollection(collectionName); foreach (TreeNode item in treeNode.Nodes) { if (item.Tag.ToString().StartsWith(COLLECTION_LIST_TAG)) { item.Nodes.Add(FillCollectionInfoToTreeNode(collectionName, mongoDB, ConKey + "/" + svrKey)); } } rtnResult = true; } } return(rtnResult); }
public void Put([FromBody] string oldName, string newName) { if (_database.CollectionExists(oldName)) { _database.RenameCollection(oldName, newName); } }
public static void InsertErpOrderPartner(string orderId, string parNr, MongoDatabase mongoDatabase, ILogger logger) { string collName = "erpOrderPartner"; if (!mongoDatabase.CollectionExists(collName)) { logger.LogDebug("Collection doesn't exist. Creating it.", collName); mongoDatabase.CreateCollection(collName); MongoCollection <BsonDocument> newErpEntriesCollection = mongoDatabase.GetCollection(collName); IndexKeysBuilder Key = IndexKeys.Ascending("orderid"); newErpEntriesCollection.CreateIndex(Key); } MongoCollection <BsonDocument> erpEntriesCollection = mongoDatabase.GetCollection(collName); MongoCursor cursor = erpEntriesCollection.Find(Query.And(Query.EQ("orderid", orderId), Query.EQ("parnr", parNr))); if (cursor.Count() == 0) { BsonDocument orderPartnerDocument = new BsonDocument(); ObjectId currentProcess_id = ObjectId.GenerateNewId(); orderPartnerDocument.Set(DBQuery.Id, currentProcess_id); orderPartnerDocument.Set("orderid", orderId); orderPartnerDocument.Set("parnr", parNr); orderPartnerDocument.Set("created", DateTime.UtcNow); erpEntriesCollection.Save(orderPartnerDocument, WriteConcern.Acknowledged); } }
/// <summary> /// Verifies the the MongoDatabase collection exists or creates it if it doesn't. /// </summary> /// <param name="logDb"></param> protected void VerifyCollection(MongoDatabase logDb) { if (!logDb.CollectionExists(_collectionName)) { logDb.CreateCollection(_collectionName, _collectionCreationOptions); } }
public static void Main(string[] args) { var client = new MongoClient ("mongodb://localhost:27017/todos"); var server = client.GetServer (); db = server.GetDatabase ("todos"); if (db == null) { Console.WriteLine ("Connection failed."); return; } // db.DropCollection ("todos"); if (!db.CollectionExists ("todos")) { var todoCollection = db.GetCollection ("todos"); // quick order by date todoCollection.CreateIndex ("created"); // enable fulltext search todoCollection.CreateIndex (IndexKeys.Text ("description")); PopulateData (); } EvalVsFind (); EvalVsFindMd5 (); TypedVsBsonDocument (); }
public static bool CreateWorldTable(this MongoDatabase db) { // only create table if it does not already exist if (db.CollectionExists("World")) { return(true); } try { // populate the table var worlds = new List <World>(10000); Parallel.For(0, 10000, i => { lock (worlds) { worlds.Add(new World() { id = i, randomNumber = SafeRandom.Instance.Next(0, 10000) + 1 }); } }); // insert new records into database var collection = db.GetCollection <World>("World"); collection.InsertBatch(worlds); return(true); } catch { return(false); } }
public void TransactionsCollection(MongoDatabase db) { if (db.CollectionExists("Transactions") == false) { db.CreateCollection("Transactions"); } }
public void UsersCollection(MongoDatabase db) { if (db.CollectionExists("Users") == false) { db.CreateCollection("Users"); } }
private static void CreateCollectionIfNecessary(MongoDatabase database) { if (!database.CollectionExists(CollectionName)) { database.CreateCollection(CollectionName); } }
static void Main(string[] args) { MongoServer ms = MongoServer.Create(); string _dbName = "docs"; MongoDatabase md = ms.GetDatabase(_dbName); if (!md.CollectionExists(_dbName)) { md.CreateCollection(_dbName); } MongoCollection <Doc> _documents = md.GetCollection <Doc>(_dbName); _documents.RemoveAll(); //add file to GridFS MongoGridFS gfs = new MongoGridFS(md); MongoGridFSFileInfo gfsi = gfs.Upload(@"c:\mongodb.rtf"); _documents.Insert(new Doc() { DocId = gfsi.Id.AsObjectId, DocName = @"c:\foo.rtf" } ); foreach (Doc item in _documents.FindAll()) { ObjectId _documentid = new ObjectId(item.DocId.ToString()); MongoGridFSFileInfo _fileInfo = md.GridFS.FindOne(Query.EQ("_id", _documentid)); gfs.Download(item.DocName, _fileInfo); Console.WriteLine("Downloaded {0}", item.DocName); Console.WriteLine("DocName {0} dowloaded", item.DocName); } Console.ReadKey(); }
public void FamilyMembersCollection(MongoDatabase db) { if (db.CollectionExists("FamilyMembers") == false) { db.CreateCollection("FamilyMembers"); } }
private void CopyCollections(params string[] exclusions) { foreach (var collectionName in _sourceMongoDatabase.GetCollectionNames()) { if (collectionName.StartsWith("system") || exclusions.Contains(exclusion => String.Equals(collectionName, exclusion))) { continue; } if (!_sourceMongoDatabase.CollectionExists(collectionName)) { Log.Warn().Message("Collection \"{0}\" was not found in the source database.", collectionName).Write(); return; } Log.Info().Message("Copying collection: {0}", collectionName).Write(); if (_mongoDatabase.CollectionExists(collectionName)) { _mongoDatabase.DropCollection(collectionName); } var source = _sourceMongoDatabase.GetCollection(collectionName); var target = _mongoDatabase.GetCollection(collectionName); target.InsertBatch(source.FindAll()); Log.Info().Message("Finished copying collection: {0}", collectionName).Write(); } }
private void CreateElevatorCollectionIfItDoesntExist() { GuardForInitialized(); if (!database.CollectionExists(SpecialCollectionNameForElevator)) { database.CreateCollection(SpecialCollectionNameForElevator); } }
private MongoCollection<T> GetCollection<T>(String suffix = "") { var collectionName = typeof (T).Name + suffix; if (!_database.CollectionExists(collectionName)) { _database.CreateCollection(collectionName); } return _database.GetCollection<T>(collectionName); }
static void connect() { server = MongoServer.Create(dbURL); database = server.GetDatabase("void"); if (!database.CollectionExists(dbName)) { database.CreateCollection(dbName); } }
/// <summary> /// GFS初始化 /// </summary> public static void InitGFS() { MongoDatabase mongoDB = SystemManager.GetCurrentDataBase(); if (!mongoDB.CollectionExists(COLLECTION_NAME_GFS_FILES)) { mongoDB.CreateCollection(COLLECTION_NAME_GFS_FILES); } }
void Initialize() { _server = MongoServer.Create(_configuration.Url); _database = _server.GetDatabase(_configuration.DefaultDatabase); if (!_database.CollectionExists(CollectionName)) _database.CreateCollection(CollectionName); _collection = _database.GetCollection<EventSubscription>(CollectionName); }
/// <summary> /// 数据库User初始化 /// </summary> public static void InitDBUser() { MongoDatabase mongoDB = SystemManager.GetCurrentDataBase(); if (!mongoDB.CollectionExists(COLLECTION_NAME_USER)) { mongoDB.CreateCollection(COLLECTION_NAME_USER); } }
void Initialize() { _server = MongoServer.Create(_configuration.Url); _database = _server.GetDatabase(_configuration.DefaultDatabase); if (!_database.CollectionExists(CollectionName)) { _database.CreateCollection(CollectionName); } _collection = _database.GetCollection(CollectionName); if (!_database.CollectionExists(IncrementalKeysCollectionName)) { _database.CreateCollection(IncrementalKeysCollectionName); } _incrementalKeysCollection = _database.GetCollection(IncrementalKeysCollectionName); }
public void tearDown() { if (wammerDb.CollectionExists("attachments")) { wammerDb.DropCollection("attachments"); } server.Close(); }
protected MongoCollection <TDto> GetOrCreateCollection(string collectionName) { if (_mongoDataBase.CollectionExists(collectionName) == false) { _mongoDataBase.CreateCollection(collectionName); } return(_mongoDataBase.GetCollection <TDto>(collectionName)); }
/// <summary> /// Js数据集初始化 /// </summary> public static void InitJavascript() { MongoDatabase mongoDB = SystemManager.GetCurrentDataBase(); if (!mongoDB.CollectionExists(COLLECTION_NAME_JAVASCRIPT)) { mongoDB.CreateCollection(COLLECTION_NAME_JAVASCRIPT); } }
protected static void DropCollections(MongoDatabase db, params string[] collectionNames) { foreach (var collectionName in collectionNames) { if (db.CollectionExists(collectionName)) { db.DropCollection(collectionName); } } }
/// <summary> /// 带有参数的CreateOption /// </summary> /// <param name="strObjTag"></param> /// <param name="collectionName"></param> /// <param name="option"></param> /// <param name="mongoDb"></param> /// <returns></returns> public static bool CreateCollectionWithOptions(string strObjTag, string collectionName, CollectionOptionsBuilder option, MongoDatabase mongoDb) { //不支持中文 JIRA ticket is created : SERVER-4412 //SERVER-4412已经在2013/03解决了 //collection names are limited to 121 bytes after converting to UTF-8. if (mongoDb == null) return false; if (mongoDb.CollectionExists(collectionName)) return false; mongoDb.CreateCollection(collectionName, option); return true; }
public MongoDocumentWriter(string connectionString, string databaseName, string collectionName) { var id = new ObjectId(); var server = new MongoClient(connectionString).GetServer(); _db = server.GetDatabase(databaseName); if (_db.CollectionExists(collectionName)) _db.DropCollection(collectionName); _db.CreateCollection(collectionName); _collection = _db.GetCollection(collectionName); }
public ObjectStore() { var connectionString = ConfigurationManager.AppSettings.Get("MONGOLAB_URI"); var server = MongoServer.Create(connectionString); _database = server.GetDatabase("appharbor_a6a88884-0e19-42c8-92ed-6ec23821b99d"); var exists = _database.CollectionExists(SubscribersKey); if (!exists) { _database.CreateCollection(SubscribersKey); } }
public override void RankAchievements() { string databaseName = "Achievements"; if (ConfigurationManager.AppSettings["MongoDbName"] != null) { databaseName = ConfigurationManager.AppSettings["MongoDbName"]; } // TODO : Get connection string from app.config // TODO : Get database name from app.config MongoServer server = MongoServer.Create(ConfigurationManager.ConnectionStrings["AchievementDatabase"].ConnectionString); //server.Settings.SocketTimeout = new TimeSpan(TimeSpan.TicksPerMinute * 5); _database = server.GetDatabase(databaseName); if (_database.CollectionExists(AchievementUsageCollectionName)) { _database.DropCollection(AchievementUsageCollectionName); } MongoCollection<Character> characterCollection = _database.GetCollection<Character>(MongoCharacterRepository.CollectionName); characterCollection.MapReduce(_mapFunction, _reduceFunction, MapReduceOptions.SetOutput(AchievementUsageCollectionName)); MongoCollection<BsonDocument> ranking = _database.GetCollection(AchievementUsageCollectionName); IList<BsonDocument> rankings = ranking.FindAll().SetSortOrder(SortBy.Descending("value.count")).ToList(); int maxRank = 0; for (int i = 0; i < rankings.Count; i++) { int achievementId = Convert.ToInt32(rankings[i]["_id"].AsDouble); Achievement achievement = AchievementRepository.Find(achievementId); if (achievement != null) { achievement.Rank = i + 1; maxRank++; AchievementRepository.Save(achievement); } } var unrankedAchievements = AchievementRepository.FindAll().Where(a => a.Rank == 0); foreach (Achievement unrankedAchievement in unrankedAchievements) { unrankedAchievement.Rank = int.MaxValue; AchievementRepository.Save(unrankedAchievement); } }
//public MongoDatabase GetDatabase() //{ // //MongoServer server = MongoServer.Create(ConnectionString); // //MongoCredential cred = new MongoCredential("test", // ////MongoCredentials cred = new MongoCredentials(UserName, PassWord); // //MongoDatabase db = server.GetDatabase(DatabaseName, cred); // //return db; //} public bool CreateCollection(MongoDatabase db, string collectionname) { try { if (db.CollectionExists(collectionname) == false) { db.CreateCollection(collectionname); return true; } else { return true; } } catch (Exception) { return false; } }
/// <summary> /// Retrieve existing or create new collection /// </summary> /// <param name="mongoDatabase">The mongo database.</param> /// <param name="collectionName">Name of the collection.</param> /// <returns></returns> private static MongoCollection<BsonDocument> GetCreateCollection(MongoDatabase mongoDatabase, string collectionName) { MongoCollection<BsonDocument> mongoCollection; if (mongoDatabase.CollectionExists(collectionName)) { mongoCollection = mongoDatabase.GetCollection<BsonDocument>(collectionName); } else { mongoCollection = mongoDatabase.GetCollection<BsonDocument>(collectionName); mongoCollection.EnsureIndex(IndexKeys.Ascending(UniqueKeyFieldName), IndexOptions.SetUnique(true)); } return mongoCollection; }