private async Task CollectionSamples()
        {
            var database = Client.GetDatabase(Constants.SamplesDatabase);

            #region Typed classes commands

            // Will create the users collection on the fly if it doesn't exists
            var personsCollection     = database.GetCollection <User>(Constants.UsersCollection);
            var bsonPersonsCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection);

            User typedUser = RandomData.GenerateUsers(1).First();
            await personsCollection.InsertOneAsync(typedUser);

            // Create another collection
            var loginsCollectionName = "logins";
            await database.CreateCollectionAsync(loginsCollectionName);

            // list collections
            var collections = (await database.ListCollectionsAsync()).ToList();
            Utils.Log(collections, "List Collections");

            // remove collection
            await database.DropCollectionAsync(loginsCollectionName);

            #region Capped collection

            // create a capped collection
            // 'size' field is required when 'capped' is true
            await database
            .CreateCollectionAsync(Constants.TravelersCollection,
                                   new CreateCollectionOptions()
            {
                Capped = true, MaxDocuments = 3, MaxSize = 10000
            });

            var travelers          = RandomData.GenerateTravelers(3);
            travelers.First().Name = "Christos";

            var travelersCollection = database
                                      .GetCollection <Traveler>(Constants.TravelersCollection);

            await travelersCollection.InsertManyAsync(travelers);

            // Max documents reached - Now let's insert another one
            await travelersCollection.InsertManyAsync(RandomData.GenerateTravelers(1));

            // Read all the docs
            var dbTravelers = await travelersCollection.Find(Builders <Traveler> .Filter.Empty).ToListAsync();

            // First user 'Christos' has been removed from the collection so that the new one can fit in

            #endregion


            #endregion
        }
        private async Task DatabaseSamples()
        {
            // Lists the databases on the server
            // Default schema for each db: {"name":"admin","sizeOnDisk":40960.0,"empty":false}

            var databases = await Client.ListDatabasesAsync();

            // iterate databases
            // Throws System.ObjectDisposedException: 'Cannot access a disposed object if ToList() or .Any() has been used
            // databases.ToList() returns a list containing all the documents returned by a cursor
            // databases.Any() determines whether the cursor contains any documents
            while (databases.MoveNext())
            {
                var currentBatch = databases.Current;
                Utils.Log(currentBatch.AsEnumerable(), "List databases");
            }

            var adminDatabase = (await Client.ListDatabasesAsync(new ListDatabasesOptions
            {
                Filter = Builders <BsonDocument> .Filter.Eq("name", "admin"),
                NameOnly = true
            })).FirstOrDefault();

            Utils.Log(adminDatabase);

            var highSizeDatabases = await Client.ListDatabases(new ListDatabasesOptions
            {
                Filter   = Builders <BsonDocument> .Filter.Gte("sizeOnDisk", 60000),
                NameOnly = true
            }).ToListAsync();

            Utils.Log(highSizeDatabases);

            // Returns the names of the databases on the server.
            var databaseNames = (await Client.ListDatabaseNamesAsync()).ToList();

            // Shell commands
            // show dbs | show databases

            // Gets a database
            IMongoDatabase adminDb = Client.GetDatabase("admin");

            // Check if database exists
            var dbNameFilter = Builders <BsonDocument> .Filter.Eq("name", "fictionDb");

            var fictionDbExists = (await Client
                                   .ListDatabasesAsync(new ListDatabasesOptions()
            {
                Filter = dbNameFilter
            }))
                                  .FirstOrDefault() != null;
        }
Exemple #3
0
        private async Task IdMemberSamples()
        {
            var database = Client.GetDatabase(Constants.SamplesDatabase);

            #region Prepare data

            // Will create the users collection on the fly if it doesn't exists
            var messagesCollection = database.GetCollection <Message>(Constants.MessagesCollection);

            #endregion

            #region Typed classes commands

            var message = new Message {
                Text = "hello world"
            };
            await messagesCollection.InsertOneAsync(message);

            Utils.Log(message.ToBsonDocument());

            #endregion
        }
        private async Task DeleteSamples()
        {
            var usersDatabase = Client.GetDatabase(Constants.SamplesDatabase);

            #region Prepare data

            // Will create the users collection on the fly if it doesn't exists
            var personsCollection = usersDatabase.GetCollection <User>(Constants.UsersCollection);

            var appPerson = RandomData.GenerateUsers(1).First();
            // Insert one document
            await personsCollection.InsertOneAsync(appPerson);

            // Insert multiple documents
            var persons = RandomData.GenerateUsers(30);

            await personsCollection.InsertManyAsync(persons);

            #endregion

            #region Typed classes commands

            // Find a person using a class filter
            var filter = Builders <User> .Filter.Eq(person => person.Id, appPerson.Id);

            // delete person
            var personDeleteResult = await personsCollection.DeleteOneAsync(filter);

            if (personDeleteResult.DeletedCount == 1)
            {
                Utils.Log($"Document {appPerson.Id} deleted");
            }

            // Delete the first document

            var emptyFilter = Builders <User> .Filter.Empty;

            // delete person
            var firstPersonDeleteResult = await personsCollection.DeleteOneAsync(emptyFilter);

            // Find multiple documents having 1200 < salary < 3500

            var salaryFilter = Builders <User> .Filter
                               .And(
                Builders <User> .Filter.Gt(person => person.Salary, 1200),
                Builders <User> .Filter.Lt(person => person.Salary, 3500)
                );

            var totalPersons = await personsCollection.Find(salaryFilter).CountDocumentsAsync();

            var personsDeleteResult = await personsCollection.DeleteManyAsync(salaryFilter);

            if (personsDeleteResult.DeletedCount.Equals(totalPersons))
            {
                Utils.Log($"{totalPersons} users deleted");
            }

            // Delete all documents
            // await personsCollection.DeleteManyAsync(Builders<User>.Filter.Empty);

            #endregion

            #region BsonDocument commands
            // we need to get the BsonDocument schema based collection
            var bsonPersonCollection = usersDatabase.GetCollection <BsonDocument>(Constants.UsersCollection);
            // Find a person using a class filter
            var bsonSingleFilter = Builders <BsonDocument> .Filter.Gt("salary", 2000);

            var bsonPersonDeleteResult = await bsonPersonCollection.DeleteOneAsync(bsonSingleFilter);

            if (bsonPersonDeleteResult.DeletedCount == 1)
            {
                Utils.Log("Person deleted");
            }

            var bsonEmptyFilter = Builders <BsonDocument> .Filter.Empty;

            // delete person
            var bsonFirstPersonDeleteResult = await bsonPersonCollection.DeleteOneAsync(bsonEmptyFilter);

            // delete many documents
            var bsonPersonsDeleteResult = await bsonPersonCollection.DeleteManyAsync(bsonSingleFilter);

            if (bsonPersonsDeleteResult.DeletedCount > 1)
            {
                Utils.Log($"Persons {bsonPersonDeleteResult.DeletedCount} deleted");
            }

            #endregion

            #region Shell commands

            /*
             * use Persons
             *
             * // delete a single document
             * db.users.deleteOne({ _id : ObjectId("5e5ff25170dc588dd0870073")})
             *
             * // delete multiple documents
             * db.users.deleteMany(
             *  { $and: [{ salary: { $gt: 1200} }, {salary: { $lt: 3500} }] }
             * )
             */

            #endregion
        }
 protected override void Init()
 {
     // Create a mongodb client
     Client = new MongoClient(Utils.DefaultConnectionString);
     Utils.DropDatabase(Client, Constants.SamplesDatabase);
 }
Exemple #6
0
        private async Task ArrayOperatorsSamples()
        {
            var database       = Client.GetDatabase(Constants.SamplesDatabase);
            var collection     = database.GetCollection <Traveler>(Constants.TravelersCollection);
            var bsonCollection = database.GetCollection <BsonDocument>(Constants.TravelersCollection);

            #region Prepare data

            var travelers = RandomData.GenerateTravelers(500);
            await collection.InsertManyAsync(travelers);

            // ElemMatch
            var greeceAndItalyTravelers = RandomData.GenerateTravelers(15);
            foreach (var grcItTraveler in greeceAndItalyTravelers)
            {
                var firstCountry  = RandomData.GenerateVisitedCountries(1).First();
                var secondCountry = RandomData.GenerateVisitedCountries(1).First();
                var random        = new Faker().PickRandom(0, 1);
                switch (random)
                {
                case 0:
                    firstCountry.Name  = "Greece";
                    secondCountry.Name = "Italy";
                    break;

                default:
                    firstCountry.Name  = "Italy";
                    secondCountry.Name = "Greece";
                    break;
                }

                grcItTraveler.VisitedCountries = new List <VisitedCountry> {
                    firstCountry, secondCountry
                };
            }

            await collection.InsertManyAsync(greeceAndItalyTravelers);

            #endregion

            #region Typed classes commands

            // Get all travelers that have visited Greece

            //same results
            var greeceTravelers = await collection.Find(t => t.VisitedCountries.
                                                        Any(c => c.Name == "Greece")).ToListAsync();

            var italyTravelers = await collection.Find(t => t.VisitedCountries
                                                       .Any(c => c.Name == "Italy")).ToListAsync();

            var greeceItalyTravelers = await collection.Find(t => t.VisitedCountries
                                                             .Any(c => c.Name == "Greece" || c.Name == "Italy")).ToListAsync();

            // using filter - same results
            var greeceVisitedFilter = Builders <Traveler> .Filter.AnyEq("visitedCountries.name", "Greece");

            greeceTravelers = await collection.Find(greeceVisitedFilter).ToListAsync();

            Utils.Log($"{greeceTravelers.Count} total travelers have visited Greece");

            var visitedTimesFilter = Builders <Traveler> .Filter.AnyEq("visitedCountries.timesVisited", 3);

            var combinedFilter = Builders <Traveler> .Filter.And(greeceVisitedFilter, visitedTimesFilter);

            var wrongResult = await collection.Find(combinedFilter).ToListAsync();

            #region size

            var fiveVisitedCountriesFilter = await collection.Find(t => t.VisitedCountries.Count == 5).ToListAsync();

            Utils.Log($"{fiveVisitedCountriesFilter.Count} total travelers have visited 5 countries exactly");

            var moreThan10VisitedCountries = await collection.Find(t => t.VisitedCountries.Count > 10).ToListAsync();

            Utils.Log($"{moreThan10VisitedCountries.Count} total travelers have visited more than 10 countries");

            #endregion

            #region elemMatch

            var visitedGreeceExactly3Times = Builders <Traveler> .Filter.ElemMatch(t => t.VisitedCountries,
                                                                                   country => country.Name == "Greece" && country.TimesVisited == 3);

            var visitedGreeceExactly3TimesTravelers = await collection.Find(visitedGreeceExactly3Times).ToListAsync();

            Utils.Log($"{visitedGreeceExactly3TimesTravelers.Count} total travelers have visited Greece exactly 3 times");

            #region multiple conditions

            var countryNameFilter = Builders <VisitedCountry> .Filter.In(c => c.Name, new[] { "Greece", "Italy" });

            var countryTimesVisitedFilter = Builders <VisitedCountry> .Filter.Eq(c => c.TimesVisited, 3);

            var visitedGreeceOrItalyExactly3Times = Builders <Traveler> .Filter
                                                    .ElemMatch(t => t.VisitedCountries,
                                                               Builders <VisitedCountry> .Filter.And(countryNameFilter, countryTimesVisitedFilter));


            var visitedGreeceOrItalyExactly3TimesTravelers = await collection.Find(visitedGreeceOrItalyExactly3Times).ToListAsync();

            Utils.Log($"{visitedGreeceOrItalyExactly3TimesTravelers.Count} total travelers have visited Greece or Italy exactly 3 times");
            #endregion

            #endregion

            #region All

            // Order doesn't matter - items are included on the array
            var climbingAndBackpackingFilter = Builders <Traveler> .Filter
                                               .All(t => t.Activities, new List <string> {
                "Backpacking", "Climbing"
            });

            var climbingAndBackpackingTravelers = await collection.Find(climbingAndBackpackingFilter).ToListAsync();

            Utils.Log($"{climbingAndBackpackingTravelers.Count} total travelers have 'Backpacking' & 'Climbing' activities");
            #endregion

            #endregion

            #region BsonDocument commands
            var bsonGreeceVisitedFilter = Builders <BsonDocument> .Filter.AnyEq("visitedCountries.name", "Greece");

            var bsonGreeceTravelers = await bsonCollection.Find(bsonGreeceVisitedFilter).ToListAsync();

            #region size

            var bsonFiveVisitedCountriesFilter = await bsonCollection.Find(
                new BsonDocument
            {
                { "visitedCountries", new BsonDocument {
                      { "$size", 5 }
                  } }
            }).ToListAsync();

            var bsonMoreThan10VisitedCountries = await bsonCollection
                                                 .Find(new BsonDocument
            {
                { "visitedCountries.10", new BsonDocument {
                      { "$exists", true }
                  } }
            }).ToListAsync();

            Utils.Log($"{moreThan10VisitedCountries.Count} total travelers have visited more than 10 countries");

            #endregion

            #region elemmMatch

            var bsonVisitedGreeceExactly3Times = Builders <BsonDocument> .Filter
                                                 .ElemMatch <BsonValue>("visitedCountries", new BsonDocument { { "name", "Greece" }, { "timesVisited", 3 } });

            var bsonVisitedGreeceExactly3TimesTravelers = await bsonCollection.Find(bsonVisitedGreeceExactly3Times).ToListAsync();

            #region multiple conditions

            var bsonVisitedGreeceOrItalyExactly3Times = Builders <BsonDocument> .Filter
                                                        .ElemMatch <BsonValue>("visitedCountries", new BsonDocument
            {
                { "name", new BsonDocument("$in", new BsonArray {
                        "Greece", "Italy"
                    }) },
                { "timesVisited", 3 }
            });

            var bsonVisitedGreeceOrItalyExactly3TimesTravelers = await bsonCollection.Find(bsonVisitedGreeceOrItalyExactly3Times).ToListAsync();

            #endregion

            #endregion

            #region All

            var bsonClimbingAndBackpackingFilter = Builders <BsonDocument> .Filter
                                                   .All("activities", new List <string> {
                "Backpacking", "Climbing"
            });

            var bsonClimbingAndBackpackingTravelers = await bsonCollection.Find(bsonClimbingAndBackpackingFilter).ToListAsync();

            #endregion

            #endregion

            #region Shell commands

#if false
            db.travelers.find({ "visitedCountries.name" : "Greece" })
        private async Task ReadSamples()
        {
            var database = Client.GetDatabase(Constants.SamplesDatabase);

            #region Prepare data

            // Will create the users collection on the fly if it doesn't exists
            var personsCollection = database.GetCollection <User>(Constants.UsersCollection);

            User appPerson = RandomData.GenerateUsers(1).First();
            // Insert one document
            await personsCollection.InsertOneAsync(appPerson);

            // Insert multiple documents
            var persons = RandomData.GenerateUsers(30);

            await personsCollection.InsertManyAsync(persons);

            #endregion

            #region Typed classes commands

            // Find a person using a class filter
            var personFilter = Builders <User> .Filter.Eq(person => person.Id, appPerson.Id);

            var personFindResult = await personsCollection.Find(personFilter).FirstOrDefaultAsync();

            Utils.Log(personFindResult.ToBsonDocument(), "Document Find with filter");

            // Find multiple documents using a filter

            var femaleGenderFilter = Builders <User> .Filter.Eq(person => person.Gender, Gender.Female);

            var females = await personsCollection.Find(femaleGenderFilter).ToListAsync();

            Utils.Log($"Found {females.Count} female persons");

            #endregion

            #region BsonDocument commands
            // we need to get the BsonDocument schema based collection
            var bsonPersonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection);

            // Create a bson filter
            var bsonPersonFilter = Builders <BsonDocument> .Filter.Eq("_id", appPerson.Id);

            // Find a person using a class filter
            var bsonPersonFindResult = await bsonPersonCollection.Find(bsonPersonFilter).FirstOrDefaultAsync();

            bsonPersonFindResult = await bsonPersonCollection.Find(new BsonDocument("_id", appPerson.Id)).FirstOrDefaultAsync();

            Utils.Log(bsonPersonFindResult);

            var bsonFemaleGenderFilter = Builders <BsonDocument> .Filter.Eq("gender", Gender.Female);

            var bsonFemales = await bsonPersonCollection.Find(bsonFemaleGenderFilter).ToListAsync();

            #endregion

            #region Shell commands

            /*
             * use Persons
             *
             * // find a single document
             * db.users.findOne(
             * {
             *  "_id": ObjectId("5e5d11fe152a428290f30245")
             * })
             *
             * // find multiple documents
             * db.users.find(
             * {
             *  "gender": 1
             * })
             */

            #endregion
        }
        private async Task UpdateSamples()
        {
            var usersDatabase = Client.GetDatabase(Constants.SamplesDatabase);

            #region Prepare data

            // Will create the users collection on the fly if it doesn't exists
            var personsCollection = usersDatabase.GetCollection <User>(Constants.UsersCollection);

            User appPerson = RandomData.GenerateUsers(1).First();
            // Insert one document
            await personsCollection.InsertOneAsync(appPerson);


            // Insert multiple documents
            var persons = RandomData.GenerateUsers(30);

            await personsCollection.InsertManyAsync(persons);

            #endregion

            #region Typed classes commands

            // Find a person using a class filter
            var filter = Builders <User> .Filter.Eq(person => person.Id, appPerson.Id);

            // update person
            var update = Builders <User> .Update.Set(person => person.Phone, "123-456-789");

            var personUpdateResult = await personsCollection.UpdateOneAsync(filter, update);

            if (personUpdateResult.MatchedCount == 1 && personUpdateResult.ModifiedCount == 1)
            {
                Utils.Log($"Document {appPerson.Id} Updated");
            }

            // Find multiple documents having 1200 < salary < 3500

            var salaryFilter = Builders <User> .Filter
                               .And(
                Builders <User> .Filter.Gt(person => person.Salary, 1200),
                Builders <User> .Filter.Lt(person => person.Salary, 3500)
                );

            var totalPersons = await personsCollection.Find(salaryFilter).CountDocumentsAsync();

            var updateDefinition =
                Builders <User> .Update.Set(person => person.Salary, 4000);

            var updateResult = await personsCollection.UpdateManyAsync(salaryFilter, updateDefinition);

            if (updateResult.MatchedCount.Equals(totalPersons))
            {
                Utils.Log($"Salary has been updated for {totalPersons}");
            }

            #endregion

            #region BsonDocument commands
            // we need to get the BsonDocument schema based collection
            var bsonPersonCollection = usersDatabase.GetCollection <BsonDocument>(Constants.UsersCollection);
            // Find a person using a class filter
            var bsonSingleFilter = Builders <BsonDocument> .Filter.Eq("_id", appPerson.Id);

            var bsonUpdate = Builders <BsonDocument> .Update.Set("phone", "123-456-678");

            var bsonPersonUpdateResult = await bsonPersonCollection.UpdateOneAsync(bsonSingleFilter, bsonUpdate);

            if (bsonPersonUpdateResult.MatchedCount == 1 && bsonPersonUpdateResult.ModifiedCount == 1)
            {
                Utils.Log("Person updated");
            }

            var bsonSalaryFilter = Builders <BsonDocument> .Filter
                                   .And(
                Builders <BsonDocument> .Filter.Gt("salary", 1200),
                Builders <BsonDocument> .Filter.Lt("salary", 3500)
                );

            var bsonUpdateDefinition =
                Builders <BsonDocument> .Update.Set("salary", 4000);

            var bsonUpdateResult = await bsonPersonCollection.UpdateManyAsync(bsonSalaryFilter, bsonUpdateDefinition);

            #endregion

            #region Shell commands

            /*
             * use Persons
             *
             * // update a single document
             * db.users.updateOne({ _id: ObjectId("5e8a35e2cc20587f34f0cc48") }, { $set: {  phone: "123-456-789" } })
             *
             * // update multiple documents
             * db.users.updateMany(
             *  { $and: [{ salary: { $gt: 1200} }, {salary: { $lt: 3500} }] },
             *  { $set: { salary: 4000  } }
             * )
             *
             */

            #endregion
        }