当前位置: 首页>>代码示例>>C#>>正文


C# MongoClient.GetDatabase方法代码示例

本文整理汇总了C#中MongoDB.Driver.MongoClient.GetDatabase方法的典型用法代码示例。如果您正苦于以下问题:C# MongoClient.GetDatabase方法的具体用法?C# MongoClient.GetDatabase怎么用?C# MongoClient.GetDatabase使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在MongoDB.Driver.MongoClient的用法示例。


在下文中一共展示了MongoClient.GetDatabase方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            var client = new MongoClient();
            var db = client.GetDatabase("CustomerDb");
            var CustColl = db.GetCollection<Customer>("Customer");

            // query customer
            var customerID = new ObjectId("xxx");

            var customers = CustColl
                            .Find(c => c.Id == customerID)
                            .SortBy(c => c.fullName)
                            .Limit(3)
                            .ToListAsync()
                            .Result;

            foreach (var customer in customers)
            {
                Console.WriteLine(customer.fullName);
            }

            //Update Customer
            var cust = customers.First();
            cust.fullName = cust.fullName.ToUpper();
        }
开发者ID:AlgebraBurger,项目名称:MongoDbConsoleRepo,代码行数:25,代码来源:Program.cs

示例2: ClothesDbContext

        public ClothesDbContext(string connectionString)
        {
            var mongoClient = new MongoClient(connectionString);
            _mongoDatabase = mongoClient.GetDatabase("ClothesWashing");

            RegisterClassMaps();
        }
开发者ID:georgiancamarasan,项目名称:ClothesWashing,代码行数:7,代码来源:ClothesDbContext.cs

示例3: Connect

        private IMongoDatabase Connect()
        {
            var client = new MongoClient(connectionString);
            var database = client.GetDatabase(databaseName);

            return database;
        }
开发者ID:shumail92,项目名称:SEDAMP-WebAPI-POC,代码行数:7,代码来源:EmailTrackingRepository.cs

示例4: PatientRepository

 /// <summary />
 public PatientRepository()
 {
     var client = new MongoClient(ConfigurationManager.ConnectionStrings["Mongo_patientcare_datamock"].ConnectionString);
     _log = new Logger("WebAPI : PatientRepository");
     _db = client.GetDatabase("patientcare_datamock");
     _patients = _db.GetCollection<BsonDocument>("Patients");
 }
开发者ID:dsb92,项目名称:patientcare,代码行数:8,代码来源:PatientRepository.cs

示例5: Main

        static void Main(string[] args)
        {
            //var mongoDB_MongoLab = "mongodb://usuario:[email protected]:61158/teste";
            var mongoDB_Local = "mongodb://localhost";

            var mongoDB = mongoDB_Local;

            var client = new MongoClient(mongoDB);

            var db = client.GetDatabase("teste");

            var clienteCollection = db.GetCollection<Cliente>("cliente");

            var novoCliente = new Cliente() { Nome = "Carlos" };
            clienteCollection.InsertOne(novoCliente);
            var id = novoCliente.Id;

            var filter = Builders<Cliente>.Filter.Eq("Nome", "Carlos");

            var cli1 = clienteCollection.Find<Cliente>(filter).FirstOrDefault();
            if (cli1 != null)
            {
                var update = Builders<Cliente>.Update.Set("Nome", "Carlos dos Santos");
                clienteCollection.UpdateOne(filter, update);
            }

            var dados = clienteCollection.Find<Cliente>(new BsonDocument()).ToListAsync().Result;

            foreach (var c in dados)
            {
                Console.WriteLine("{0} - {1}",c.Id,c.Nome);
            }
        }
开发者ID:carloscds,项目名称:AulaMongo,代码行数:33,代码来源:Program.cs

示例6: MongoDbBase

 public MongoDbBase(string connectionString, string database)
 {
     this.connectionString = connectionString;
     this.database = database;
     Client = new MongoClient(connectionString);
     Database = Client.GetDatabase(database);
 }
开发者ID:Flavien,项目名称:mongodb-storage,代码行数:7,代码来源:MongoDbBase.cs

示例7: GetDatabase

        public IMongoDatabase GetDatabase()
        {
            var client = new MongoClient(this.ConnectionString);
            var db = client.GetDatabase(this.DatabaseName);

            return db;
        }
开发者ID:ni4ka7a,项目名称:Molybdenum-Team,代码行数:7,代码来源:MongoProvider.cs

示例8: MainAsync

        private static async Task MainAsync(string[] args)
        {
            var client = new MongoClient();
            var db = client.GetDatabase("photos");

            var albums = db.GetCollection<BsonDocument>("albums");

            var result = await albums
                .Aggregate()
                .Unwind("images")
                .Group(@"{ _id: ""$images"" }")
                .ToListAsync();

            var nonOrphansIds = result
                .Select((p) => (int)p["_id"])
                .ToList();

            var images = db.GetCollection<BsonDocument>("images");

            var allImages = await images
                .Find(new BsonDocument())
                .ToListAsync();

            List<int> orphanIds = new List<int>();

            foreach (var image in allImages)
            {
                int id = (int)image["_id"];

                if (!nonOrphansIds.Contains(id))
                {
                    await images.DeleteOneAsync(string.Format(CultureInfo.InvariantCulture, "{{_id: {0}}}", id));
                }
            }
        }
开发者ID:martincostello,项目名称:mongodb-university,代码行数:35,代码来源:Program.cs

示例9: LoadTimelineConcat

        protected void LoadTimelineConcat()
        {
            // Response.Write("start    ");

            MongoClient mclient = new MongoClient(GlobalVariables.mongolabConection);
            var db = mclient.GetDatabase(GlobalVariables.mongoDatabase);

            var collection = db.GetCollection<DocumentInfo>("DocumentsCollection");


            var filter = Builders<DocumentInfo>.Filter.Eq("name", "Ilciuc"); 

            //await collection.Find(new BsonDocument()).ForEachAsync(d => jsString += d+",");
            jsString = "";
            collection.Find(new BsonDocument()).ForEachAsync(d => jsString += "{\"id\":\""
               + ReplaceToHTML(d.id) + "\",\"title\" : \"" + ReplaceToHTML(d.title) + "\",\"startdate\" : \"" + d.startdate
               + "\",\"enddate\" : \"" + endDate(d.enddate) + "\",\"importance\" : \""
               + 50 + "\",\"description\" : \"" + ReplaceToHTML(d.description) + "\",\"link\" : \""
               + ReplaceToHTML(d.link)  + "\",\"image\" : \"" + ReplaceToHTML(d.image)  + "\"},").Wait();
            //await collection.Find(filter).ForEachAsync(d => jsString += "{\"id\":\"" + d.id + "\",\"title\" : \"" + d.title + "\",\"startdate\" : \"" + d.startdate + "\",\"enddate\" : \"" + d.enddate + "\",\"importance\" : \"" + d.importance + "\",\"description\" : \"" + d.description + "\",\"link\" : \"" + d.link + "\",\"image\" : \"" + d.image + "\"},");


            jsonData = "[{" +
         "\"id\": \"main_data\"," +
         "\"title\": \"TimeTrail\"," +
         "\"initial_zoom\": \"40\"," +
         //"\"focus_date\": \"1998-03-11 12:00:00\","+
         "\"image_lane_height\": 50," +
         "\"events\":[" + jsString.TrimEnd(',') + "]" +
     "}]";

            //Response.Write("    end");
        }
开发者ID:Sergiuu17,项目名称:Timeline,代码行数:33,代码来源:Home.aspx.cs

示例10: GetCollection

 private static IMongoCollection<FormMongoEntity> GetCollection()
 {
     var client = new MongoClient();
     var db = client.GetDatabase("joinzjazure");
     var collection = db.GetCollection<FormMongoEntity>("Forms");
     return collection;
 }
开发者ID:CMLibrary-Dev-Team,项目名称:Joinzjazure,代码行数:7,代码来源:ApplicationFormMongoDbStore.cs

示例11: RunAsync

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">[repository] [source collection name] [target collection name]</param>
        /// <returns></returns>
        public async Task RunAsync(string[] args)
        {
            var repository = args[0];

            var sourceCollectionName = args[1];

            var targetCollectionName = args[2];

            var client = new MongoClient(_connectionStringProvider.GetConnectionString(repository));

            IMongoDatabase _database = client.GetDatabase(repository);

            IMongoCollection<BsonDocument> targetCollection = _database.GetCollection<BsonDocument>(targetCollectionName);

            IMongoCollection<BsonDocument> sourceCollection = _database.GetCollection<BsonDocument>(sourceCollectionName);

            await sourceCollection.Find(new BsonDocument()).ForEachAsync(async (thread) => {
                foreach (var user in thread.GetElement(targetCollectionName).Value.AsBsonArray)
                {
                    var filter = Builders<BsonDocument>.Filter.Eq("id", user.ToBsonDocument().GetElement("id").Value);

                    var count = await targetCollection.Find(filter).CountAsync();

                    if (count == 0)
                    {
                        await targetCollection.InsertOneAsync(user.ToBsonDocument());
                    }
                }
            });
        }
开发者ID:Edward-Zhou,项目名称:easy-analysis,代码行数:35,代码来源:ImportNewUsers.cs

示例12: BtnSubmitData_Click

        // ---- Ubacivanje podataka u bazi ----
        private void BtnSubmitData_Click(object sender, EventArgs e)
        {
            // ---- Provera ispravnosti podataka ----
            if (String.IsNullOrWhiteSpace(TbPunoIme.Text))
            {
                MessageBox.Show("Unesi Puno ime trenera!");
                return;
            }
            else if (String.IsNullOrWhiteSpace(TbMestoRodjenja.Text))
            {
                MessageBox.Show("Unesi mesto rodjenja trenera!");
                return;
            }
            else if (String.IsNullOrWhiteSpace(TbTrenutniKlub.Text))
            {
                MessageBox.Show("Unesi trenutni klub(reprezentaciju) koju trenira trener!");
                return;
            }
            Trener forSave = new Trener();
            forSave.PunoIme = StringCleaner.checkString(TbPunoIme.Text);
            forSave.MestoRodjenja = StringCleaner.checkString(TbMestoRodjenja.Text);
            forSave.TrenutniKlub = StringCleaner.checkString(TbTrenutniKlub.Text);
            forSave.TrenerskaKarijera = StringCleaner.checkString(RtbTrenerskaKarijera.Text);
            forSave.Uspesi = StringCleaner.checkString(RtbUspesi.Text);
            forSave.DatumRodjenja = StringCleaner.checkString(dateTimePicker1.Value.ToShortDateString());

            var _client = new MongoClient();
            var _database = _client.GetDatabase("test");

            var collection = _database.GetCollection<BsonDocument>("treneri");
            var filter = new BsonDocument() 
            {
                {"PunoIme",TbPunoIme.Text}
            };

            var filterForUniqueCheck = Builders<BsonDocument>.Filter.Eq("PunoIme", this.TbPunoIme.Text);

            var document = forSave.ToBsonDocument();
            //test if  exists
            var test = collection.Find(filterForUniqueCheck).Count();

            if(test == 0)
            {
                collection.InsertOne(document);
                if (slikaTrenera != null)
                {
                    AuxLib.AddImageToGridFS(slikaTrenera, forSave.PunoIme, format);
                }
                
                MessageBox.Show("Uspesno dodat novi trener!");
            }
            else
            {
                //TO DO : URADITI UPDATE SLIKE (AuxLib treba da ima remove image i remove mp3 i da se izbaci slika i ubaci nova);
                collection.ReplaceOne(filter, document);
                MessageBox.Show("Uspesno azuriran trener!");
            }
            
            
        }
开发者ID:perinjo,项目名称:MongoDB,代码行数:61,代码来源:FDodavanjeTrenera.cs

示例13: GetMongoConnection

 /// <summary>
 /// Gets the mongo connection.
 /// </summary>
 /// <param name="connectionString">The connection string.</param>
 /// <returns></returns>
 internal static MongoDatabase GetMongoConnection(String connectionString)
 {
     UserClassMap.Register();
     var mongoUrl = MongoUrl.Create(connectionString);
     var server = new MongoClient(connectionString).GetServer();
     return server.GetDatabase(mongoUrl.DatabaseName);
 }
开发者ID:netdragoon,项目名称:MongoProviders,代码行数:12,代码来源:ClientMongo.cs

示例14: LogEntryRepository

 public LogEntryRepository(MongoClient mongoClient, IConfiguration configuration, string databaseName = "Kelpie")
 {
     _mongoClient = mongoClient;
     _configuration = configuration;
     _database = _mongoClient.GetDatabase(databaseName);
     _collection = _database.GetCollection<LogEntry>("LogEntry");
 }
开发者ID:floradu88,项目名称:kelpie,代码行数:7,代码来源:LogEntryRepository.cs

示例15: MainAsync

        private async Task MainAsync()
        {
            var connStr = "mongodb://localhost:27017";
            var client = new MongoClient(connStr);
            var db = client.GetDatabase("store");
            var col = db.GetCollection<Product>("products");
            await db.DropCollectionAsync("products");

            Random random = new Random();

            List<string> descriptions = new List<string>() { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj" };
            List<string> categories = new List<string>() { "sports", "food", "clothing", "electronics" };
            List<string> brands = new List<string>() { "GE", "nike", "adidas", "toyota", "mitsubishi" };

            var docs = Enumerable.Range(0, 100)
                .Select(i => new Product
                {
                    Id = i,
                    SKU = String.Format("{0:D8}", i),
                    Price = random.NextDouble() * (100 - 1) + 1,
                    Description = descriptions[random.Next(descriptions.Count)],
                    Category = categories[random.Next(categories.Count)],
                    Brand = brands[random.Next(brands.Count)],
                    Reviews = new List<Review>(),
                });
            await col.InsertManyAsync(docs);

            await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Ascending(x => x.SKU), new CreateIndexOptions() { Unique = true });
            await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Descending(x => x.Price));
            await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Ascending(x => x.Description));
            await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Ascending(x => x.Category).Ascending(x => x.Brand));
            await col.Indexes.CreateOneAsync("{'reviews.author':1}");
        }
开发者ID:azmikamis,项目名称:M101NAssignments,代码行数:33,代码来源:Week4Assignment.cs


注:本文中的MongoDB.Driver.MongoClient.GetDatabase方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。