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 WriteConcernSamples() { var personsDatabase = Client.GetDatabase(Constants.SamplesDatabase); #region Prepare data var writeConcern = new WriteConcern(w: new Optional <WriteConcern.WValue>("0"), journal: false); var user = RandomData.GenerateUsers(1).First(); var usersCollection = personsDatabase.GetCollection <User>(Constants.UsersCollection) .WithWriteConcern(writeConcern); // Requests no acknowledgment of the write operation // no user id available! // Command insert failed: cannot use non-majority 'w' mode 0 when a host is not a member of a replica set.' await usersCollection.InsertOneAsync(user); List <User> users = RandomData.GenerateUsers(3000); await usersCollection.InsertManyAsync(users); var totalUsers = await usersCollection.CountDocumentsAsync(Builders <User> .Filter.Empty); var unassigned = users.Where(u => u.Id.Equals(default(ObjectId))); #endregion #region Typed classes commands #endregion #region BsonDocument commands #endregion #region Shell commands #if false #endif #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 }
private async Task LogicalOperatorsSamples() { var database = Client.GetDatabase(Constants.SamplesDatabase); var collection = database.GetCollection <User>(Constants.UsersCollection); var bsonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection); #region Prepare data var users = RandomData.GenerateUsers(1000); await collection.InsertManyAsync(users); #endregion #region Typed classes commands #region and // and on simple properties - all male doctors var maleFilter = Builders <User> .Filter.Eq(u => u.Gender, Gender.Male); var doctorFilter = Builders <User> .Filter.Eq(u => u.Profession, "Doctor"); var maleDoctorsFilter = Builders <User> .Filter.And(maleFilter, doctorFilter); var maleDoctors = await collection.Find(maleDoctorsFilter).ToListAsync(); Utils.Log($"{maleDoctors.Count} total users are male Doctors"); ////////////////////////////////////////////////////////////////////////////////////// // and combined with other operators // - all a) female witch are b) either teacher or nurse AND c) having salary between 2000-3200 var femaleFilter = Builders <User> .Filter.Eq(u => u.Gender, Gender.Female); var teacherOrNurseFilter = Builders <User> .Filter .In(u => u.Profession, new[] { "Teacher", "Nurse", "Dentist" }); var salaryFilter = Builders <User> .Filter.And( Builders <User> .Filter.Gte(u => u.Salary, 2000), Builders <User> .Filter.Lte(u => u.Salary, 3200)); var combinedFilter = Builders <User> .Filter.And(femaleFilter, teacherOrNurseFilter, salaryFilter); var matchedUsers = await collection.Find(combinedFilter).ToListAsync(); Utils.Log($"{matchedUsers.Count} total users are female Teacher or Nurse or Dentist, with 2000 < salary < 3200"); #endregion #region not // all users that are females, hence not males var notMaleFilter = Builders <User> .Filter.Not( Builders <User> .Filter.Eq(u => u.Gender, Gender.Male) ); var femaleUsers = await collection.Find(notMaleFilter).ToListAsync(); Utils.Log($"{femaleUsers.Count} users have female gender"); #endregion #region or // users with salary either < 1500 (too low) or > 4000 (too high) var orSalaryFilter = Builders <User> .Filter.Or( Builders <User> .Filter.Lt(u => u.Salary, 1500), Builders <User> .Filter.Gt(u => u.Salary, 4000)); var lowOrHighSalaryUsers = await collection.Find(orSalaryFilter).ToListAsync(); Utils.Log($"{lowOrHighSalaryUsers.Count} users have salary either too low or too high"); #endregion #region nor // users with profession other than Doctor, salary other than < 4500 // should fail all conditions var norFilter = Builders <User> .Filter.And( Builders <User> .Filter.Not(Builders <User> .Filter.Eq(u => u.Profession, "Doctor")), Builders <User> .Filter.Not(Builders <User> .Filter.Lt(u => u.Salary, 4500))); var norUsers = await collection.Find(norFilter).ToListAsync(); Utils.Log($"{norUsers.Count} users aren't doctors and have salary greater than 4500"); var firstFilterToFail = Builders <User> .Filter.Eq(u => u.Profession, "Doctor"); var secondFilterToFail = Builders <User> .Filter.Lt(u => u.Salary, 4500); var extensionNorFilter = Builders <User> .Filter.Nor(firstFilterToFail, secondFilterToFail); var extensionUsers = await collection.Find(norFilter).ToListAsync(); #endregion #endregion #region BsonDocument commands #region and var bsonMaleFilter = Builders <BsonDocument> .Filter.Eq("gender", Gender.Male); var bsonDoctorFilter = Builders <BsonDocument> .Filter.Eq("profession", "Doctor"); var bsonMaleDoctorsFilter = Builders <BsonDocument> .Filter.And(bsonMaleFilter, bsonDoctorFilter); var bsonMaleDoctors = await bsonCollection.Find(bsonMaleDoctorsFilter).ToListAsync(); ////////////////////////////////////////////////////////////////////////////////////// var bsonFemaleFilter = Builders <BsonDocument> .Filter.Eq("gender", Gender.Female); var bsonTeacherOrNurseFilter = Builders <BsonDocument> .Filter .In("profession", new[] { "Teacher", "Nurse", "Dentist" }); var bsonSalaryFilter = Builders <BsonDocument> .Filter.And( Builders <BsonDocument> .Filter.Gte("salary", 2000), Builders <BsonDocument> .Filter.Lte("salary", 3200)); var bsonCombinedFilter = Builders <BsonDocument> .Filter .And(bsonFemaleFilter, bsonTeacherOrNurseFilter, bsonSalaryFilter); var bsonMatchedUsers = await bsonCollection.Find(bsonCombinedFilter).ToListAsync(); #endregion #region not // all users that are females, hence not females var bsonNotMaleFilter = Builders <BsonDocument> .Filter.Not( Builders <BsonDocument> .Filter.Eq("gender", Gender.Male) ); var bsonFemaleUsers = await bsonCollection.Find(bsonNotMaleFilter).ToListAsync(); #endregion #region or var bsonOrSalaryFilter = Builders <BsonDocument> .Filter.Or( Builders <BsonDocument> .Filter.Lt("salary", 1500), Builders <BsonDocument> .Filter.Gt("salary", 4000)); var bsonLowOrHighSalaryUsers = await bsonCollection.Find(bsonOrSalaryFilter).ToListAsync(); #endregion #region nor var bsonNorFilter = Builders <BsonDocument> .Filter.And( Builders <BsonDocument> .Filter.Not(Builders <BsonDocument> .Filter.Eq("profession", "Doctor")), Builders <BsonDocument> .Filter.Not(Builders <BsonDocument> .Filter.Lt("salary", 4500))); var bsonNorUsers = await bsonCollection.Find(bsonNorFilter).ToListAsync(); #endregion #endregion #region Shell commands #if false db.users.find({ $and:[{ profession: { $eq: "Doctor" } }, { gender: { $eq: 0 } }] })
private async Task FindDocumentsSamples() { var database = Client.GetDatabase(Constants.SamplesDatabase); var collection = database.GetCollection <User>(Constants.UsersCollection); var bsonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection); #region Prepare data var users = RandomData.GenerateUsers(1000); for (int i = 0; i < users.Count; i++) { if (i >= 30 && i < 50) { users[i].Address.City = "Athens"; } } await collection.InsertManyAsync(users); var sampleUser = RandomData.GenerateUsers(1).First(); sampleUser.Email = "*****@*****.**"; sampleUser.Phone = "123-456-789"; await collection.InsertOneAsync(sampleUser); #endregion #region Typed classes commands // empty filter var emptyFilter = Builders <User> .Filter.Empty; // first user var firstUser = await collection.Find(emptyFilter).FirstOrDefaultAsync(); // all users var allUsers = await collection.Find(emptyFilter).ToListAsync(); // Get the first document with equality filter on a simple property var sampleUserFilter = Builders <User> .Filter.Eq(u => u.Email, sampleUser.Email); var dbSampleUser = await collection.Find(sampleUserFilter).FirstOrDefaultAsync(); // Find multiple documents with equality filter on a simple property var doctorsFilter = Builders <User> .Filter.Eq(u => u.Profession, "Doctor"); var doctors = await collection.Find(doctorsFilter).ToListAsync(); // same result with .Find // doctors = collection.Find(doctorsFilter).ToCursor(); Utils.Log($"{doctors.Count} doctors found"); // Query on an embedded field, eg. address.city // find all users with address.city = Athens var athensCityFilter = Builders <User> .Filter.Eq(u => u.Address.City, "Athens"); var athensUsers = await collection.Find(athensCityFilter).ToListAsync(); Utils.Log($"{athensUsers.Count} total users live in Athens"); // Query on array property // find all users that have Basketball on their favorite sports - // doesn't have to be the only item on the array, may have more favorite sports as well var basketballFilter = Builders <User> .Filter.AnyEq(u => u.FavoriteSports, "Basketball"); var usersHaveBasketball = await collection.Find(basketballFilter).ToListAsync(); Utils.Log($"{usersHaveBasketball.Count} have Basketball on their favorite sports collection"); // find all users that have ONLY Soccer on their favorite sports var onlySoccerFilter = Builders <User> .Filter .Eq(u => u.FavoriteSports, new List <string> { "Soccer" }); var soccerUsers = await collection.Find(onlySoccerFilter).ToListAsync(); Utils.Log($"{soccerUsers.Count} have only Soccer on their favorite sports collection"); #endregion #region BsonDocument commands var bsonEmptyDocument = Builders <BsonDocument> .Filter.Empty; var bsonFirstUser = await bsonCollection.Find(new BsonDocument()).FirstOrDefaultAsync(); var bsonAllUsers = await bsonCollection.Find(bsonEmptyDocument).ToListAsync(); var sampleBsonUserFilter = Builders <BsonDocument> .Filter.Eq("email", sampleUser.Email); var dbBsonSampleUser = await bsonCollection.Find(sampleBsonUserFilter).FirstOrDefaultAsync(); var bsonDoctorsFilter = Builders <BsonDocument> .Filter.Eq("profession", "Doctor"); var bsonDoctors = await bsonCollection.Find(bsonDoctorsFilter).FirstOrDefaultAsync(); var bsonAthensCityFilter = Builders <BsonDocument> .Filter.Eq("address.city", "Athens"); var bsonAthensUsers = await bsonCollection.Find(bsonAthensCityFilter).ToListAsync(); var bsonBasketballFilter = Builders <BsonDocument> .Filter.AnyEq("favoriteSports", "Basketball"); var bsonUsersHaveBasketball = await bsonCollection.Find(bsonBasketballFilter).ToListAsync(); var bsonOnlySoccerFilter = Builders <BsonDocument> .Filter .Eq("favoriteSports", new List <string>() { "Soccer" }); var bsonSoccerUsers = await bsonCollection.Find(bsonOnlySoccerFilter).ToListAsync(); #endregion #region Shell commands #if false db.users.findOne({})
private async Task ProjectionSamples() { var personsDatabase = Client.GetDatabase(Constants.SamplesDatabase); var collection = personsDatabase.GetCollection <User>(Constants.UsersCollection); var usersQueryableCollection = personsDatabase.GetCollection <User>(Constants.UsersCollection).AsQueryable(); var bsonCollection = personsDatabase.GetCollection <BsonDocument>(Constants.UsersCollection); var tripsDatabase = Client.GetDatabase(Constants.SamplesDatabase); var travelersCollection = tripsDatabase.GetCollection <Traveler>(Constants.TravelersCollection); #region Prepare data await collection.InsertManyAsync(RandomData.GenerateUsers(500)); await travelersCollection.InsertManyAsync(RandomData.GenerateTravelers(500)); #endregion #region Typed classes commands // exclude id, return only gender and date of birth var simpleProjection = Builders <User> .Projection .Exclude(u => u.Id) .Include(u => u.Gender) .Include(u => u.DateOfBirth); var simpleProjectionResults = await collection .Find(Builders <User> .Filter.Empty) .Project(simpleProjection) .ToListAsync(); // return full name (first & last name), gender ('Male' or 'Female'), age //var lastNameProjection = Builders<User>.Projection.Expression(u => u.FirstName + " " + u.LastName); var customProjection = Builders <User> .Projection.Expression(u => new { fullName = $"{u.FirstName} {u.LastName}", fullNameUpper = ToUpperCase($"{u.FirstName} {u.LastName}"), gender = u.Gender.ToString(), age = DateTime.Today.Year - u.DateOfBirth.Year }); var results = await collection.Find(Builders <User> .Filter.Empty) .Project(customProjection) .ToListAsync(); foreach (var result in results) { Utils.Log(result.ToBsonDocument()); } #endregion #region BsonDocument commands var bsonSimpleProjection = Builders <BsonDocument> .Projection .Exclude("_id") .Include("gender") .Include("dateOfBirth"); var bsonSimpleProjectionResults = await bsonCollection .Find(Builders <BsonDocument> .Filter.Empty) .Project(bsonSimpleProjection) .ToListAsync(); #endregion #region Linq var linqSimpleProjection = from u in usersQueryableCollection select new { fullName = u.FirstName + " " + u.LastName, fullNameUpper = ToUpperCase($"{u.FirstName} {u.LastName}"), gender = u.Gender == Gender.Male ? "Male" : "Female", age = DateTime.Now.Year - u.DateOfBirth.Year }; Utils.Log($"Query built: {linqSimpleProjection}"); var linqSimpleProjectionResults = await linqSimpleProjection.ToListAsync(); #endregion #region Shell commands #if false db.users.aggregate([
private async Task UpdateDocumentsDefinitions() { var database = Client.GetDatabase(Constants.SamplesDatabase); var collection = database.GetCollection <User>(Constants.UsersCollection); var bsonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection); #region Prepare data await collection.InsertManyAsync(RandomData.GenerateUsers(1000)); #endregion #region Typed classes commands #region set var firstUserFilter = Builders <User> .Filter.Empty; var allusers = await collection.Find(firstUserFilter).ToListAsync(); // update a single field var updateNameDefinition = Builders <User> .Update.Set(u => u.FirstName, "Chris"); var updateNameResult = await collection.UpdateOneAsync(firstUserFilter, updateNameDefinition); Utils.Log($"{updateNameResult.ModifiedCount} user's name was updated"); // update multiple fields var multiUpdateDefinition = Builders <User> .Update .Set(u => u.Phone, "123-456-789") .Set(u => u.Website, "https://chsakell.com") .Set(u => u.FavoriteSports, new List <string> { "Soccer", "Basketball" }); var multiUpdateResult = await collection.UpdateOneAsync(firstUserFilter, multiUpdateDefinition); Utils.Log($"Multiple user's fields were updated"); #endregion #region inc // can be used with negative values to decrease var incrementSalaryDefinition = Builders <User> .Update.Inc(u => u.Salary, 450); var incrementSalaryResult = await collection.UpdateOneAsync(firstUserFilter, incrementSalaryDefinition); Utils.Log($"User's salary has been increased"); #endregion // combine inc with set var incWithSetUpdateDefinition = Builders <User> .Update.Set(u => u.FirstName, "Chris") .Inc(u => u.Salary, 450); var incWithSetUpdateResult = await collection.UpdateOneAsync(firstUserFilter, incWithSetUpdateDefinition); #region min // preparation - set current salary to 3000 await collection.UpdateOneAsync(firstUserFilter, Builders <User> .Update.Set(u => u.Salary, 3000)); // update only if the new value is less than the current // would not update if the new salary was > 3000 var minUpdateDefinition = Builders <User> .Update.Min(u => u.Salary, 2000); var minUpdateResult = await collection.UpdateOneAsync(firstUserFilter, minUpdateDefinition); Utils.Log($"{minUpdateResult.ModifiedCount} user's salary has been updated (decreased - min)"); #endregion #region max // preparation - set current salary to 3000 await collection.UpdateOneAsync(firstUserFilter, Builders <User> .Update.Set(u => u.Salary, 3000)); // update only if the new value is greater than the current // would not update if the new salary was < 3000 var maxUpdateDefinition = Builders <User> .Update.Max(u => u.Salary, 3500); var maxUpdateResult = await collection.UpdateOneAsync(firstUserFilter, maxUpdateDefinition); Utils.Log($"{maxUpdateResult.ModifiedCount} user's salary has been updated (increased - max)"); #endregion #region mul // preparation - set current salary to 1000 await collection.UpdateOneAsync(firstUserFilter, Builders <User> .Update.Set(u => u.Salary, 1000)); // set salary X 2 var mulUpdateDefinition = Builders <User> .Update.Mul(u => u.Salary, 2); var mulUpdateResult = await collection.UpdateOneAsync(firstUserFilter, mulUpdateDefinition); Utils.Log($"{mulUpdateResult.ModifiedCount} user's salary has been doubled (mul)"); #endregion #region unset // remove the website field for the first user var removeWebsiteDefinition = Builders <User> .Update.Unset(u => u.Website); var removeWebsiteFieldUpdateResult = await collection.UpdateOneAsync(firstUserFilter, removeWebsiteDefinition); Utils.Log("Website field entirely removed from the first document"); #region caution //var removeSalaryDefinition = Builders<User>.Update.Unset(u => u.Salary); //var removeSalaryFieldUpdateResult = // await collection.UpdateOneAsync(firstUserFilter, removeSalaryDefinition); //var firstUser = await collection.Find(firstUserFilter).FirstOrDefaultAsync(); #endregion #endregion #region rename // rename the phone field to phoneNumber for the first user var renamePhoneDefinition = Builders <User> .Update.Rename(u => u.Phone, "phoneNumber"); var renamePhoneFieldUpdateResult = await collection.UpdateOneAsync(firstUserFilter, renamePhoneDefinition); Utils.Log("Phone field renamed to phone"); // Switch back to phone await collection.UpdateOneAsync(firstUserFilter, Builders <User> .Update.Rename("phoneNumber", "phone")); #endregion #endregion #region BsonDocument commands #region set var bsonFirstUserFilter = Builders <BsonDocument> .Filter.Empty; // single field var bsonUpdateNameDefinition = Builders <BsonDocument> .Update.Set("firstName", "John"); var bsonUpdateNameResult = await bsonCollection.UpdateOneAsync(bsonFirstUserFilter, bsonUpdateNameDefinition); // update multiple fields var bsonMultiUpdateDefinition = Builders <BsonDocument> .Update .Set("phone", "123-456-789") .Set("website", "https://chsakell.com") .Set("favoriteSports", new List <string> { "Soccer", "Basketball" }); var bsonMultiUpdateResult = await bsonCollection.UpdateOneAsync(bsonFirstUserFilter, bsonMultiUpdateDefinition); #endregion #region inc var bsonIncrementSalaryDefinition = Builders <BsonDocument> .Update.Inc("salary", 450); var bsonIncrementSalaryResult = await bsonCollection .UpdateOneAsync(bsonFirstUserFilter, bsonIncrementSalaryDefinition); #endregion // combine inc with set var bsonIncWithSetUpdateDefinition = Builders <BsonDocument> .Update.Set("firstName", "Chris").Inc("salary", 450); var bsonIncWithSetUpdateResult = await bsonCollection .UpdateOneAsync(bsonFirstUserFilter, bsonIncWithSetUpdateDefinition); #region min // preparation - set current salary to 3000 await bsonCollection.UpdateOneAsync(bsonFirstUserFilter, Builders <BsonDocument> .Update.Set("salary", 3000)); // update only if the new value is less than the current // would not update if the new salary was > 3000 var bsonMinUpdateDefinition = Builders <BsonDocument> .Update.Min("salary", 2000); var bsonMinUpdateResult = await bsonCollection .UpdateOneAsync(bsonFirstUserFilter, bsonMinUpdateDefinition); #endregion #region max // preparation - set current salary to 3000 await bsonCollection.UpdateOneAsync(bsonFirstUserFilter, Builders <BsonDocument> .Update.Set("salary", 3000)); // update only if the new value is greater than the current // would not update if the new salary was < 3500 var bsonMaxUpdateDefinition = Builders <BsonDocument> .Update.Max("salary", 3500); var bsonMaxUpdateResult = await bsonCollection .UpdateOneAsync(bsonFirstUserFilter, bsonMaxUpdateDefinition); #endregion #region mul // preparation - set current salary to 1000 await bsonCollection.UpdateOneAsync(bsonFirstUserFilter, Builders <BsonDocument> .Update.Set("salary", 1000)); // set salary X 2 var bsonMulUpdateDefinition = Builders <BsonDocument> .Update.Mul("salary", 2); var bsonMulUpdateResult = await bsonCollection.UpdateOneAsync(bsonFirstUserFilter, bsonMulUpdateDefinition); #endregion #region unset // remove the website field for the first user var bsonRemoveWebsiteDefinition = Builders <BsonDocument> .Update.Unset("website"); var bsonRemoveWebsiteFieldUpdateResult = await bsonCollection.UpdateOneAsync(bsonFirstUserFilter, bsonRemoveWebsiteDefinition); #endregion #region rename // rename the phone field to phoneNumber for the first user var bsonRenamePhoneDefinition = Builders <BsonDocument> .Update.Rename("phone", "phoneNumber"); var bsonRenamePhoneFieldUpdateResult = await bsonCollection.UpdateOneAsync(bsonFirstUserFilter, bsonRenamePhoneDefinition); // Switch back to phone await bsonCollection.UpdateOneAsync(bsonFirstUserFilter, Builders <BsonDocument> .Update.Rename("phoneNumber", "phone")); #endregion #endregion #region Shell commands #if false db.users.updateOne({}, { $set: { firstName: "Chris" } });
private async Task ComparisonOperatorsSamples() { var database = Client.GetDatabase(Constants.SamplesDatabase); var collection = database.GetCollection <User>(Constants.UsersCollection); var bsonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection); #region Prepare data var users = RandomData.GenerateUsers(1000); await collection.InsertManyAsync(users); #endregion #region Typed classes commands var totalUsers = await collection.CountDocumentsAsync(Builders <User> .Filter.Empty); // Equal // Case sensitive matters! var equalPilotsFilter = Builders <User> .Filter.Eq(u => u.Profession, "Pilot"); var pilots = await collection.Find(equalPilotsFilter).ToListAsync(); Utils.Log($"Among {totalUsers} users, {pilots.Count} are pilots"); // Not equal // Case sensitive matters! var notEqualDoctorsFilter = Builders <User> .Filter.Ne(u => u.Profession, "Doctor"); var notDoctors = await collection.Find(notEqualDoctorsFilter).ToListAsync(); Utils.Log($"Among {totalUsers} users, {notDoctors.Count} aren't doctors"); // Greater than var filterGreaterThan = Builders <User> .Filter.Gt(u => u.Salary, 3500); var greaterThan3500 = await collection.Find(filterGreaterThan).ToListAsync(); // Greater or equal than var filterGreaterOrEqualThan = Builders <User> .Filter.Gte(u => u.Salary, 4500); var greaterOrEqualThan4500 = await collection.Find(filterGreaterOrEqualThan).ToListAsync(); // Less than var filterLessThan = Builders <User> .Filter.Lt(u => u.Salary, 2500); var lessThan2500 = await collection.Find(filterLessThan).ToListAsync(); // Greater or equal than var filterLessOrEqualThan = Builders <User> .Filter.Lte(u => u.Salary, 1500); var lessThanOrEqual1500 = await collection.Find(filterLessOrEqualThan).ToListAsync(); Utils.Log($"Salary Greater than 3500 total: {greaterThan3500.Count}{Environment.NewLine}" + $"Salary Greater or equal to 4500 total: {greaterOrEqualThan4500.Count}{Environment.NewLine}" + $"Salary Less than 2500 total: {lessThan2500.Count}{Environment.NewLine}" + $"Salary Less than or equal to 1500 total: {lessThanOrEqual1500.Count}{Environment.NewLine}"); // In var medicalProfessionsFilter = Builders <User> .Filter.In(u => u.Profession, new[] { "Dentist", "Pharmacist", "Nurse" }); var medicalUsers = await collection.Find(medicalProfessionsFilter).ToListAsync(); Utils.Log($"{medicalUsers.Count} users have medical related profession"); // Not In var nonMedicalProfessionsFilter = Builders <User> .Filter.Nin(u => u.Profession, new[] { "Dentist", "Pharmacist", "Nurse" }); var nonMedicalUsers = await collection.Find(nonMedicalProfessionsFilter).ToListAsync(); Utils.Log($"{nonMedicalUsers.Count} users have no medical related profession"); #endregion #region BsonDocument commands // Equal // Case sensitive matters! var bsonEqualPilotsFilter = Builders <BsonDocument> .Filter.Eq("profession", "Pilot"); var bsonPilots = await bsonCollection.Find(bsonEqualPilotsFilter).ToListAsync(); // Not equal var bsonNotEqualDoctorsFilter = Builders <BsonDocument> .Filter.Ne("profession", "Doctor"); var bsonNotDoctors = await bsonCollection.Find(bsonNotEqualDoctorsFilter).ToListAsync(); // Greater than var bsonFilterGreaterThan = Builders <BsonDocument> .Filter.Gt("salary", 3500); var bsonGreaterThan3500 = await bsonCollection.Find(bsonFilterGreaterThan).ToListAsync(); // Greater or equal than var bsonFilterGreaterOrEqualThan = Builders <BsonDocument> .Filter.Gte("salary", 4500); var bsonGreaterOrEqualThan4500 = await bsonCollection.Find(bsonFilterGreaterOrEqualThan).ToListAsync(); // Less than var bsonFilterLessThan = Builders <BsonDocument> .Filter.Lt("salary", 2500); var bsonLessThan2500 = await bsonCollection.Find(bsonFilterLessThan).ToListAsync(); // Greater or equal than var bsonFilterLessOrEqualThan = Builders <BsonDocument> .Filter.Lte("salary", 1500); var bsonLessThanOrEqual1500 = await bsonCollection.Find(bsonFilterLessOrEqualThan).ToListAsync(); // In var bsonMedicalProfessionsFilter = Builders <BsonDocument> .Filter.In("profession", new[] { "Dentist", "Pharmacist", "Nurse" }); var bsonMedicalUsers = await bsonCollection.Find(bsonMedicalProfessionsFilter).ToListAsync(); // Not In var bsonNotMedicalProfessionsFilter = Builders <BsonDocument> .Filter.Nin("profession", new[] { "Dentist", "Pharmacist", "Nurse" }); var bsonNotMedicalUsers = await bsonCollection.Find(bsonNotMedicalProfessionsFilter).ToListAsync(); #endregion #region Shell commands #if false db.users.find({ salary: { $gt: 3500 } })
private async Task MatchStageSamples() { var personsDatabase = Client.GetDatabase(Constants.SamplesDatabase); var travelersDatabase = Client.GetDatabase(Constants.SamplesDatabase); var personsCollection = personsDatabase.GetCollection <User>(Constants.UsersCollection); var personsBsonCollection = personsDatabase.GetCollection <BsonDocument>(Constants.UsersCollection); var travelersCollection = travelersDatabase.GetCollection <Traveler>(Constants.TravelersCollection); var travelersBsonCollection = travelersDatabase.GetCollection <BsonDocument>(Constants.TravelersCollection); #region Prepare data await personsCollection.InsertManyAsync(RandomData.GenerateUsers(500)); await travelersCollection.InsertManyAsync(RandomData.GenerateTravelers(500)); #endregion #region Typed classes commands var aggregate = personsCollection.Aggregate() .Match(Builders <User> .Filter.Gte(u => u.Salary, 3500) & Builders <User> .Filter.Lte(u => u.Salary, 5000)); var highSalaryUsers = await aggregate.ToListAsync(); Utils.Log($"{highSalaryUsers.Count} users found with high salary"); var visitedGreeceExactly3Times = Builders <Traveler> .Filter .ElemMatch(t => t.VisitedCountries, country => country.Name == "Greece" && country.TimesVisited == 3); // match with project var simpleProjection = Builders <Traveler> .Projection .Include(t => t.Name) .Include(t => t.Age) .Include(t => t.VisitedCountries); var greeceAggregate = travelersCollection .Aggregate() .Match(visitedGreeceExactly3Times) .Project(simpleProjection); var greeceVisited3Times = await greeceAggregate.ToListAsync(); #endregion #region BsonDocument commands var bsonAggregate = personsBsonCollection.Aggregate() .Match(Builders <BsonDocument> .Filter.Gte("salary", 3500) & Builders <BsonDocument> .Filter.Lte("salary", 5000)); var bsonHighSalaryUsers = await bsonAggregate.ToListAsync(); var bsonSimpleProjection = Builders <BsonDocument> .Projection .Include("name") .Include("age") .Include("visitedCountries"); var bsonVisitedGreeceExactly3Times = Builders <BsonDocument> .Filter .ElemMatch <BsonValue>("visitedCountries", new BsonDocument { { "name", "Greece" }, { "timesVisited", 3 } }); var bsonGreeceAggregate = travelersBsonCollection .Aggregate() .Match(bsonVisitedGreeceExactly3Times) .Project(bsonSimpleProjection); var bsonGreeceVisited3Times = await bsonGreeceAggregate.ToListAsync(); #endregion #region Shell commands #if false db.users.aggregate([
private async Task ElementOperatorsSamples() { var database = Client.GetDatabase(Constants.SamplesDatabase); var usersCollection = database.GetCollection <User>(Constants.UsersCollection); var usersBsonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection); var productsCollection = database.GetCollection <Product>(Constants.ProductsCollection); var productsBsonCollection = database.GetCollection <BsonDocument>(Constants.ProductsCollection); #region Prepare data var users = RandomData.GenerateUsers(500); var products = RandomData.GenerateProducts(500); await usersCollection.InsertManyAsync(users); await productsCollection.InsertManyAsync(products); #endregion #region Typed classes commands #region regex var gmailFilter = Builders <User> .Filter.Regex(u => u.Email, new BsonRegularExpression("/gmail/")); var gmailUsers = await usersCollection.Find(gmailFilter).ToListAsync(); Utils.Log($"{gmailUsers.Count} users found to have gmail acounts"); #endregion #region expr #endregion #region text productsCollection.Indexes.CreateOne(new CreateIndexModel <Product> (Builders <Product> .IndexKeys.Text(p => p.Name))); var searchFilter = Builders <Product> .Filter.Text("shirt"); var searchFilterQuery = searchFilter.Render(BsonSerializer.SerializerRegistry.GetSerializer <Product>(), BsonSerializer.SerializerRegistry); var shirtsProducts = await productsCollection.Find(searchFilter).ToListAsync(); Utils.Log($"There are {shirtsProducts.Count} total shirt products"); #endregion #endregion #region BsonDocument commands #region regex var bsonGmailFilter = Builders <BsonDocument> .Filter .Regex("email", new BsonRegularExpression("/gmail/")); var bsonGmailUsers = await usersBsonCollection.Find(bsonGmailFilter).ToListAsync(); #endregion #region text var bsonSearchFilter = Builders <BsonDocument> .Filter.Text("shirt"); var bsonShirtsProducts = await productsBsonCollection.Find(bsonSearchFilter).ToListAsync(); #endregion #endregion #region Shell commands #if false db.users.find({ "email" : { $regex: / gmail / } }) #endif #endregion }
private async Task InsertSamples() { 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); User appPerson = RandomData.GenerateUsers(1).First(); // Insert one document await personsCollection.InsertOneAsync(appPerson); // Insert multiple documents var persons = RandomData.GenerateUsers(10); await personsCollection.InsertManyAsync(persons); #endregion #region BsonDocument commands var personsBsonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection); var bsonPerson = new BsonDocument { { "gender", 1 }, { "firstName", "Johh" }, { "lastName", "Doe" }, { "userName", "Kimberly12" }, { "avatar", "https://s3.amazonaws.com/uifaces/faces/twitter/benefritz/128.jpg" }, { "email", "*****@*****.**" }, { "dateOfBirth", new BsonDateTime(DateTime.Now.AddYears(-25)) }, { "address", new BsonDocument { { "street", "113 Al Points" }, { "suite", "Apt. 697" }, { "city", "South Murrayshire" }, { "state", "South Dakota" }, { "zipCode", "35038" }, { "geo", new BsonDocument() { { "lat", 87.333 }, { "lng", -116.99 } } } } }, { "phone", "392-248-7338 x083" }, { "website", "terry.biz" }, { "company", new BsonDocument() { { "name", "Bode - Hills" }, { "catchPhrase", "Total composite service-desk" }, { "bs", "morph customized bandwidth" } } }, { "salary", 1641 }, { "monthlyExpenses", 3009 }, { "favoriteSports", new BsonArray { "Basketball", "MMA" } }, { "profession", "Doctor" } }; await personsBsonCollection.InsertOneAsync(bsonPerson); var bsonUser = BsonDocument.Parse(@"{ 'gender' : 1, 'firstName' : 'Kimberly', 'lastName' : 'Ernser', 'userName' : 'Kimberly12', 'avatar' : 'https://s3.amazonaws.com/uifaces/faces/twitter/benefritz/128.jpg', 'email' : '*****@*****.**', 'dateOfBirth' : ISODate('1996-06-10T23:55:56.029+03:00'), 'address' : { 'street' : '113 Al Points', 'suite' : 'Apt. 697', 'city' : 'South Murrayshire', 'state' : 'South Dakota', 'zipCode' : '35038', 'geo' : { 'lat' : 87.4034, 'lng' : -116.5628 } }, 'phone' : '392-248-7338 x083', 'website' : 'terry.biz', 'company' : { 'name' : 'Bode - Hills', 'catchPhrase' : 'Total composite service-desk', 'bs' : 'morph customized bandwidth' }, 'salary' : 1641, 'monthlyExpenses' : 3009, 'favoriteSports' : [ 'Basketball', 'MMA', 'Volleyball', 'Ice Hockey', 'Water Polo', 'Moto GP', 'Beach Volleyball' ], 'profession' : 'Photographer' }"); await personsBsonCollection.InsertOneAsync(bsonUser); await personsBsonCollection.InsertOneAsync(appPerson.ToBsonDocument()); #endregion #region Shell commands /* * use Persons * db.users.insertOne({ * 'firstName': 'Lee', * 'lastName': 'Brown', * 'userName': '******', * 'avatar': 'https://s3.amazonaws.com/uifaces/faces/twitter/ccinojasso1/128.jpg', * 'email': '*****@*****.**', * 'dateOfBirth': '1984-01-16T21:31:27.87666', * 'address': { * 'street': '2552 Bernard Rapid', * 'suite': 'Suite 199', * 'city': 'New Haskell side', * 'zipCode': '78425-0411', * 'geo': { * 'lat': -35.8154, * 'lng': -140.2044 * } * }, * 'phone': '1-500-790-8836 x5069', * 'website': 'javier.biz', * 'company': { * 'name': 'Kuphal and Sons', * 'catchPhrase': 'Organic even-keeled monitoring', * 'ns': 'open-source brand e-business' * }, * 'salary': NumberDecimal(3000) * }) */ #endregion }
private async Task UpdateDocumentsDefinitions() { var database = Client.GetDatabase(Constants.SamplesDatabase); var usersCollection = database.GetCollection <User>(Constants.UsersCollection); var usersBsonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection); var socialNetworkCollection = database.GetCollection <SocialAccount>(Constants.SocialNetworkCollection); var bsonSocialNetworkBsonCollection = database.GetCollection <BsonDocument>(Constants.SocialNetworkCollection); #region Prepare data await usersCollection.InsertManyAsync(RandomData.GenerateUsers(1000)); #endregion #region Typed classes commands #region Replace // replace the first document entirely // requires [BsonIgnoreIfDefault] if id not available var newUser = RandomData.GenerateUsers(1).First(); // newUser.Id = ObjectId.GenerateNewId(); this would cause an exception newUser.FirstName = "Chris"; newUser.LastName = "Sakellarios"; newUser.Website = "https://github.com/chsakell"; var replaceOneResult = await usersCollection.ReplaceOneAsync(Builders <User> .Filter.Empty, newUser); Utils.Log($"First user document has been replaced with new user"); // if id is available then set it on the new doc before replacing the old one var firstDbUser = await usersCollection.Find(Builders <User> .Filter.Empty).FirstOrDefaultAsync(); newUser.Id = firstDbUser.Id; newUser.Website = "https://chsakell.com"; var firstUser = await usersCollection.FindOneAndReplaceAsync( Builders <User> .Filter.Eq(u => u.Id, firstDbUser.Id), newUser, new FindOneAndReplaceOptions <User> { ReturnDocument = ReturnDocument.After }); // move properties var friends = new List <string> { "John", "Maria", "Catherine" }; var blocked = new List <string> { "Jake", "Helen" }; var username = "******"; var socialAccountBefore = new BsonDocument() { { "username", username }, { "friends", new BsonArray(friends) }, { "blocked", new BsonArray(blocked) } }; await bsonSocialNetworkBsonCollection.InsertOneAsync(socialAccountBefore); // replace and move properties... var socialAccountAfter = new SocialAccount { Username = username, RelationShips = new RelationShips { Friends = friends, Blocked = blocked } }; await socialNetworkCollection .ReplaceOneAsync(Builders <SocialAccount> .Filter .Eq(ac => ac.Username, username), socialAccountAfter); #endregion #region upsert // update a document but if not found then insert it var microsoftCeo = RandomData.GenerateUsers(1).First(); microsoftCeo.FirstName = "Satya"; microsoftCeo.LastName = "Nadella"; microsoftCeo.Company.Name = "Microsoft"; // returns null without upsert true var satyaNadellaFirstAttemptResult = await usersCollection .FindOneAndReplaceAsync <User>(u => u.Company.Name == "Microsoft", microsoftCeo); var addOrReplaceSatyaNadellaUser = await usersCollection .FindOneAndReplaceAsync <User>(u => u.Company.Name == "Microsoft", microsoftCeo, new FindOneAndReplaceOptions <User>() { IsUpsert = true, ReturnDocument = ReturnDocument.After }); var addOrReplaceSatyaNadellaResult = await usersCollection .ReplaceOneAsync <User>(u => u.Company.Name == "Microsoft Corp", microsoftCeo, new ReplaceOptions() { IsUpsert = true }); #endregion #endregion #region BsonDocument commands newUser.FirstName = "Christos"; newUser.LastName = "Sakellarios"; newUser.Website = "https://github.com/chsakell"; var bsonReplaceOneResult = await usersBsonCollection .ReplaceOneAsync(new BsonDocument(), newUser.ToBsonDocument()); var bsonAddOrReplaceSatyaNadellaUser = await usersBsonCollection .FindOneAndReplaceAsync( Builders <BsonDocument> .Filter.Eq("company.name", "Microsoft Corp"), microsoftCeo.ToBsonDocument(), new FindOneAndReplaceOptions <BsonDocument>() { IsUpsert = true, ReturnDocument = ReturnDocument.After }); var bsonFirstUser = await usersBsonCollection.FindOneAndReplaceAsync( Builders <BsonDocument> .Filter.Eq("_id", firstDbUser.Id), newUser.ToBsonDocument(), new FindOneAndReplaceOptions <BsonDocument> { ReturnDocument = ReturnDocument.After }); #endregion #region Shell commands #if false db.users.replaceOne({},
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 LimitSkipSamples() { var personsDatabase = Client.GetDatabase(Constants.SamplesDatabase); var usersCollection = personsDatabase.GetCollection <User>(Constants.UsersCollection); var usersQueryableCollection = personsDatabase.GetCollection <User>(Constants.UsersCollection).AsQueryable(); var usersBsonCollection = personsDatabase.GetCollection <BsonDocument>(Constants.UsersCollection); #region Prepare data await usersCollection.InsertManyAsync(RandomData.GenerateUsers(100)); var skipSize = 3; var limitSize = 3; #endregion #region Typed #region Top Level // In find order doesn't matter but in pipelines it does! // Order users by their birth date, older persons first var topLevelProjection = Builders <User> .Projection .Exclude(u => u.Id) .Include(u => u.UserName) .Include(u => u.DateOfBirth); var topLevelProjectionResults = await usersCollection.Find(Builders <User> .Filter.Empty) .Project(topLevelProjection) .SortBy(u => u.DateOfBirth) .Skip(skipSize) .Limit(limitSize) .ToListAsync(); foreach (var topLevelProjectionResult in topLevelProjectionResults) { Utils.Log(topLevelProjectionResult.ToJson()); } var linqTopLevelResults = await usersQueryableCollection .Select(u => new { u.UserName, u.DateOfBirth }) .OrderBy(u => u.DateOfBirth) .Skip(skipSize) .Take(limitSize) .ToListAsync(); #endregion #endregion #region BsonDocument commands var bsonTopLevelProjection = Builders <BsonDocument> .Projection .Exclude("_id") .Include("userName") .Include("dateOfBirth"); var bsonTopLevelProjectionResults = await usersBsonCollection.Find(Builders <BsonDocument> .Filter.Empty) .Project(bsonTopLevelProjection) .SortBy(doc => doc["dateOfBirth"]) .Skip(skipSize) .Limit(limitSize) .ToListAsync(); #endregion #region Shell commands #if false db.users.aggregate([
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 }
private async Task GroupStageSamples() { var database = Client.GetDatabase(Constants.SamplesDatabase); var collection = database.GetCollection <User>(Constants.UsersCollection); var bsonCollection = database.GetCollection <BsonDocument>(Constants.UsersCollection); #region Prepare data await collection.InsertManyAsync(RandomData.GenerateUsers(1000)); #endregion #region Typed classes commands #region group on single field // group by profession var singleFieldAggregate = collection.Aggregate() .Group(u => u.Profession, ac => new { profession = ac.Key, total = ac.Sum(u => 1) }); var groupedProfessions = await singleFieldAggregate.ToListAsync(); Utils.Log("Grouped by profession:"); foreach (var group in groupedProfessions) { Utils.Log($"{group.profession}: {group.total}"); } #endregion #region group by embedded document field // group by address state and sorted var embeddedDocFieldAggregate = collection.Aggregate() .Group(u => u.Address.State, ac => new { state = ac.Key, total = ac.Sum(u => 1) }) .SortBy(group => group.total); // ASC var groupedPerCountry = await embeddedDocFieldAggregate.ToListAsync(); Utils.Log("Grouped by address state sorted:"); foreach (var group in groupedPerCountry) { Utils.Log($"{group.state}: {group.total}"); } #endregion #endregion #region excercices // a) find users with 1500 < 3000 salary, // b) group by gender & display average monthly expenses // c) sort in descending order on avg monthly expenses // truncation resulted in data loss => https://jira.mongodb.org/browse/CSHARP-2399 var excercice1Aggregate = collection.Aggregate() .Match(Builders <User> .Filter.Gte(u => u.Salary, 1500) & Builders <User> .Filter.Lte(u => u.Salary, 3000)) .Group(u => u.Gender, ac => new { gender = ac.Key, averageMonthlyExpenses = ac.Average(u => u.MonthlyExpenses), total = ac.Sum(u => 1) }) .Project(group => new { Gender = group.gender == 0 ? "Male" : "Female", AverageMonthlyExpenses = group.averageMonthlyExpenses, Total = group.total }) .SortByDescending(group => group.AverageMonthlyExpenses); var excercice1Result = await excercice1Aggregate.ToListAsync(); Utils.Log("Grouped by gender with average monthly expenses"); var linqQuery = collection.AsQueryable() .Where(u => u.Salary > 1500 && u.Salary < 3000) .GroupBy(u => u.Gender) .Select(ac => new { gender = ac.Key, averageMonthlyExpenses = Math.Ceiling(ac.Average(u => u.MonthlyExpenses)), total = ac.Sum(u => 1) }) .OrderBy(group => group.total); var excercice1LinqResult = linqQuery.ToList(); foreach (var group in excercice1LinqResult) { Utils.Log($"{group.gender}: total - {group.total}, average monthly expenses - {group.averageMonthlyExpenses}"); } // count births by year var excercice2Aggregate = collection.Aggregate() .Group(u => u.DateOfBirth.Year, ac => new { year = ac.Key, total = ac.Sum(u => 1) }) .SortByDescending(group => group.year); var excercice2AggregateResult = await excercice2Aggregate.ToListAsync(); #endregion #region Shell commands #if false db.users.aggregate([