Mongo DB Driver
What is Mongo DB?
MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas, It provides a convenient and efficient way to perform CRUD (Create, Read, Update, Delete) operations, as well as advanced queries and aggregation tasks on MongoDB data.
How it Works?
Asynchronous Operations: The driver supports asynchronous programming, allowing you to write efficient and responsive applications by leveraging async/await patterns.
LINQ Support: You can use LINQ (Language-Integrated Query) to write expressive and readable queries against our MongoDB collections, making it easier to work with data.
Automatic Object Mapping: The driver can map C# objects to MongoDB documents and vice versa, simplifying the process of storing and retrieving data.
Authentication and Authorization: It supports various authentication mechanisms, ensuring secure access to our MongoDB databases. Role-based access control (RBAC) can also be enforced.
High Availability: The driver can handle MongoDB replica sets and sharded clusters, providing fault tolerance and high availability.
Indexing: You can define and manage indexes on our MongoDB collections to optimize query performance.
Fundamentals
Fields
In MongoDB, a "field" refers to a key-value pair within a document. MongoDB is a NoSQL database, and its data model is based on BSON (Binary JSON) documents, which consist of fields where each field has a name (key) and a value. Fields are the basic building blocks of MongoDB documents and are used to store data in a structured format.
Here's an example of a document with fields:
{
"_id": {
"$binary": {
"base64": "leAaTkzfrUSPAsPuUtXnqw==",
"subType": "03"
}
},
"TenantId": {
"$binary": {
"base64": "G7+UhYqf50WkYsG/2LgBlA==",
"subType": "03"
}
},
"Name": {
"Neutral": "Euro",
"Locales": {}
}
}
Builders
Builders provide a more structured way to create complex queries by chaining methods together. The FilterDefinitionBuilder<TDocument> and SortDefinitionBuilder</TDocument> classes can be used for filter and sort operations, respectively.
This builder will help us construct the filter conditions.
Builders<SalutationTypeModel>.Filter
This builder is used to create a sorting definition, sorts documents in descending order or ascending order using Ascending or Descending after.
Builders<SalutationTypeModel>.Sort
You can also use builders to Update:
Builders<SalutationTypeModel>.Update.HandleUpdate(CurrentUserReference)
Filters
Filters are used to define the criteria for selecting documents from a collection. They allow you to specify which documents match your query based on various conditions. Filters are typically used with methods like Find to retrieve documents from a collection that match the specified criteria.
Here's is how a filter applies to our solution
Builders<SalutationTypeModel>.Filter.Eq(r => r.Id, data.Id) & (
Builders<SalutationTypeModel>.Filter.Ne(r => r.IsDeleted, data.IsDeleted) |
Builders<SalutationTypeModel>.Filter.Ne(r => r.Name, data.Name)
In this example we use the Eq(Equal) and a Ne(NonEqual) method to create a filter that matches documents where the "Id" is equal to "data.Id, the Ne Method does the opposite. This approach allows you to create complex filters using a more structured and fluent syntax, making it easier to build queries with multiple conditions. You can chain various filter conditions together using logical operators like And, Or, and Not to create sophisticated queries as needed.
Lambda Expressions
The driver supports using lambda expressions to render projections. When you define a Find() projection with the Expression() method to create a lambda expression, the driver inspects the expression to determine which fields are referenced and automatically constructs a server-side projection to return only those fields.
this, r => r.CreatedBy, data.CreatedBy
Queries
In MongoDB, queries are used to retrieve data from a collection that matches specific criteria or conditions. When working with MongoDB in C#, you can use the MongoDB C# Driver to construct and execute queries against our database.
Basic Query: You can create a basic query to retrieve documents from a collection by specifying filter conditions. The filter is built using the FilterDefinition class, and you can use operators like Eq (equals), Gt (greater than), Lt (less than), and more to define your criteria.
Complex Queries: MongoDB allows you to construct complex queries by combining multiple filter conditions using logical operators like And, Or, and Not. This flexibility enables you to create sophisticated queries to match various criteria.
Projection: You can specify which fields to include or exclude from the query results using projection. This can help reduce the amount of data retrieved and improve query performance.
Sorting: You can sort query results in ascending or descending order based on one or more fields using the Sort method.
Pagination: To retrieve a limited number of documents at a time, you can use methods like Limit and Skip to implement pagination in your queries.
Indexing: MongoDB allows you to create indexes on fields to improve query performance, especially for frequently used queries.
Executing Queries: Finally, you execute the query using the Find method, which returns a cursor that can be converted to a list of documents, or you can use other methods like FirstOrDefault, Single, or Count depending on your needs.
Projections
In MongoDB, projections allow you to control which fields from a document are returned in the query results. Projections are useful when you want to retrieve only specific fields from a document rather than the entire document. This can help reduce network and processing overhead, especially when dealing with large documents or when you need only a subset of the data.
Here's an example on our code:
IAggregateFluent<AddressModel> projection = PersonCollection.Aggregate().Match(personFilter)
.Unwind(x => x.PersonalData.Contacts.Addresses)
.ReplaceRoot<AddressModel>($"${nameof(PersonModel.PersonalData)}.{nameof(PersonalDataModel.Contacts)}.{nameof(ContactsModel.Addresses)}")
.Match(Builders<AddressModel>.Filter.OryonAuthorization(this, $"{nameof(ContactsModel.Addresses)}.{nameof(AddressModel.Companies)}", isList: true));
Logging
Logging with ILogger in MongoDB applied to C# applications allows you to capture and manage various log events, including MongoDB-related operations, errors, and application events, in a consistent and flexible manner. You can choose different logging providers and levels to suit our application's requirements and easily switch between providers for different environments or debugging purposes.
public AreaRepository(ILogger<AreaRepository> logger, PeopleDatabaseConfiguration databaseConfiguration, IServiceProvider)