Minimum requirements to access MongoDB server.
Since it is not mandatory for the Database or Collections to actually exist in MongoDB when writing the program, we can specify any Database or collection name.
Below sample code can be used to connect to MongoDB.
Please find the below sample program for Connecting to the MongoDB server and inserting documents.
- Visual studio 2013 or later is required.
- .NET 4.5 is required.
- Latest MongoDB driver, even older versions can be used.
Since it is not mandatory for the Database or Collections to actually exist in MongoDB when writing the program, we can specify any Database or collection name.
Below sample code can be used to connect to MongoDB.
1 2 3 4 5 6 7 8 9 10 11 | /// Provide the IP address and Port to connect to. var ConnectionString = "mongodb://localhost:27017"; /// Creating a Mongo Client. var Client = new MongoClient(ConnectionString); /// Specify the Database to connect to. Database is "school". var db = Client.GetDatabase("school"); /// Specify the collection in which we need to Create/Query/Insert/Delete/Update. var col = db.GetCollection<BsonDocument>("teachers"); |
Please find the below sample program for Connecting to the MongoDB server and inserting documents.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; using MongoDB.Driver.Linq; namespace Learn_Mongodb_1 { class Program { static void Main(string[] args) { MainAsync(args).Wait(); Console.WriteLine("Completed"); Console.ReadLine(); } static async Task MainAsync(string[] args) { /// Mongodb server calling commands should be written in ASYNC functions. /// /// Provide the IP address and Port to connect to. var ConnectionString = "mongodb://localhost:27017"; /// Creating a Mongo Client. var Client = new MongoClient(ConnectionString); /// Specify the Database to connect to. Database is "school". var db = Client.GetDatabase("school"); /// Specify the collection in which we need to Create/Query/Insert/Delete/Update. var col = db.GetCollection<BsonDocument>("teachers"); var teacher = new BsonDocument { {"Name" , "Smith"}, {"Designation" , "Professor"}, {"Subject" , "Economics"} }; await col.InsertOneAsync(teacher); } } } |
After executing the above code we can find the above mentioned Database, Collection and record inserted.
No comments:
Post a Comment