Click here to Skip to main content
15,881,636 members
Articles / Database Development / NoSQL

Beginners' guide to using MongoDB 4.0.2 and the official C# driver

Rate me:
Please Sign up or sign in to vote.
4.92/5 (43 votes)
16 Sep 2018CPOL13 min read 198.9K   3.4K   101  
Highlights the latest developments in both the Mongo open-source document database and the open-source official C# driver.
namespace TestMongo
{
    using System;

    using MongoDB.Driver;
    using MongoDB.Driver.Builders;

    public partial class Program
    {
        #region Methods

        private static void Main()
        {
          
            // const string connectionString = "mongodb://myUserName:MyPassword@linus.mongohq.com:myPortNumber/";
            const string connectionString = "mongodb://localhost/?replicaSet=myReplSet&readPreference=primary";
           // const string connectionString = "mongodb://localhost";
          
            // Create a MongoClient object by using the connection string
            var client = new MongoClient(connectionString);

            //Use the MongoClient to access the server
            MongoServer server = client.GetServer();

            // Use the server to access the 'test' database
            MongoDatabase database = server.GetDatabase("test");
     
            //Builds new Collection if 'entities' is not found
            MongoCollection<ClubMember> collection = database.GetCollection<ClubMember>("entities");

            long count = collection.Count();

            var random = new Random();
            if (count == 0)
            {
                Console.WriteLine("Collection is empty.");
                Console.WriteLine("Enter the number of people to add");

                string ans = Console.ReadLine();
                int counter;
                int.TryParse(ans, out counter);
                Console.WriteLine("Adding {0} new ClubMembers", counter);

                BuildClubMembers(collection, random, counter);
            }
            else
            {
                Console.WriteLine("Number of ClubMembers in Collection {0}", count);
            }

            //Build an index if it is not already built
            IndexKeysBuilder keys = IndexKeys.Ascending("Lastname", "Forename").Descending("Age");
           
            //Add an optional name- useful for admin
            IndexOptionsBuilder options = IndexOptions.SetName("myIndex");
          
            //This locks the database while the index is being built
            collection.EnsureIndex(keys, options);

            Console.WriteLine("List of ClubMembers in collection ...");
            MongoCursor<ClubMember> members = collection.FindAll();
            foreach (ClubMember clubMember in members)
            {
                clubMember.PrintDetailsToScreen();
            }

            DemoLinq(collection);
            DemoQueryBuilder(server,database,collection);
            DemoAggregation(collection);
            DemoMapReduce(collection);
            DemoGridFS(database);


            Console.WriteLine("Press return key to exit or");
            Console.WriteLine("enter 'yes' to empty the Database and exit");
            string emptyDb = Console.ReadLine();
            if (emptyDb == "yes")
            {
                collection.RemoveAll();
            }
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Wales Wales
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions