Esempio n. 1
0
        public static bool Init(string cString, string dbName, out IMongoDatabase mongoDb)
        {
            Console.WriteLine("\nConnect to MongoDB Server...");
            try
            {
                // Create Database and All Tables
                mongoDb = new MongoClient(cString).GetDatabase(dbName);

                // Remove Collections If Exist
                mongoDb.DropCollection(nameof(PersonData), nameof(Person));

                // Create Collection
                mongoDb.CreateCollection(nameof(PersonData));
                // Add Schema Validator
                var personDataSchema = new
                {
                    collMod   = nameof(PersonData),
                    validator = new BsonDocument("$jsonSchema", new
                    {
                        bsonType   = "object",
                        required   = new[] { nameof(PersonData.PersonId), nameof(PersonData.Value) },
                        properties = new
                        {
                            PersonId = new { bsonType = "objectId" },
                            Value    = new { bsonType = "double" }
                        }
                    }.ToBsonDocument())
                }.ToBsonDocument();
                mongoDb.RunCommand <BsonDocument>(personDataSchema);

                // Create Collection
                mongoDb.CreateCollection(nameof(Person));
                // Add Schema Validator
                var personSchema = new
                {
                    collMod   = nameof(Person),
                    validator = new BsonDocument("$jsonSchema", new
                    {
                        bsonType   = "object",
                        required   = new[] { nameof(Person.Name) },
                        properties = new
                        {
                            Name = new { bsonType = "string" }
                        }
                    }.ToBsonDocument())
                }.ToBsonDocument();
                mongoDb.RunCommand <BsonDocument>(personSchema);
            }
            catch (Exception e)
            {
                // Show Error Message and Exit
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Message);
                Console.ReadKey();

                mongoDb = null;
                return(false);
            }

            Console.Write("Ready For ");
            if (SingleQuery)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("Single");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("Multi");
            }
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.Write(" Query Mode CRUD\n");
            return(true);
        }