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 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 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 }