Click here to Skip to main content
15,891,136 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 199.7K   3.4K   101  
Highlights the latest developments in both the Mongo open-source document database and the open-source official C# driver.
namespace MongoDBDemoAsync
{
    using System;
    using System.Threading.Tasks;

    using MongoDB.Bson;
    using MongoDB.Driver;
    using MongoDBDemoAsync.Classes;

    internal class Program
    {
        #region Public Methods and Operators

        public static void Main()
        {
            Console.WriteLine("****Running on UI type SynchronizationContext****\n");
            var syncContext = new SingleThreadSynchronizationContext();
            syncContext.Run(MainAsync);
            //The thread does not return here until MainAsync's continuation has finished
        }

        #endregion

        #region Methods

        private static async Task MainAsync()
        {
            const string connectionString = Constants.ConnectionString;
            //const string connectionString = Constants.ReplicaSetConnectionString;
            var client = new MongoClient(connectionString);

            // Use the client to access the 'TestMongoDB' database
            IMongoDatabase database = client.GetDatabase(Constants.DatebaseName);
            IMongoCollection<ClubMember> carClubCollection = database.GetCollection<ClubMember>(Constants.CarClubCollection);
            var mapReduceCollection = database.GetCollection<BsonDocument>(Constants.MapReduceCollection);
            var demoManager = new DemoManager(carClubCollection);
            long count = await carClubCollection.CountDocumentsAsync(new BsonDocument());
            if (count == 0)
            {
                Console.WriteLine("About to add new  club members to the database");
                count = ConsoleHelper.GetNumberFromUser("Enter total number of club members", Constants.MinimumMembership, Constants.MaximumMembership);
                var clubMembersBuilder = new ClubMembersBuilder();
                Console.WriteLine($"Adding {count} new ClubMembers");
                await clubMembersBuilder.BuildClubMembersAsync(carClubCollection, count);
            }
            else
            {
                Console.WriteLine($"Number of ClubMembers in Collection {count}");
            }
            //Build an index if it is not already built
            IndexKeysDefinition<ClubMember> keys =
                Builders<ClubMember>.IndexKeys.Ascending("Lastname").Ascending("Forename").Descending("Age");
            //Add an optional name- useful for admin
            var options = new CreateIndexOptions { Name = Constants.IndexName };
            var indexModel = new CreateIndexModel<ClubMember>(keys, options);
            await carClubCollection.Indexes.CreateOneAsync(indexModel);
            bool isContinue = true;
            while (isContinue)
            {
                isContinue = await demoManager.PromptNextDemoAsync();
            }
            Console.WriteLine("Please press the return key to empty the collections and exit ");
            Console.ReadLine();
            var emptyFilter = new BsonDocument();
            await carClubCollection.DeleteManyAsync(emptyFilter);
            await mapReduceCollection.DeleteManyAsync(emptyFilter);
            //  database.DropCollection(Constants.MapReduceCollection);
            // database.DropCollection(Constants.CarClubCollection);
        }

        #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