Image

You can see there are a few attributes and types coming from the MongoDB NuGet packages.

NoSQL databases are usually very well suited for working with non-relational hierarchical data. In this example, we are using MongoDB types expecially made for geo-locations, like GeoJson2DGeographicCoordinates.

 

Retrieve the database and the collection

In eShopOnContainers, we have created a custom database context where we implement the code to retrieve the database and the MongoCollections, as in the following code.

ImageRetrieve the data

ImageIn C# code, like Web API controllers or custom Repositories implementation, you can write similar code to the following when querying through the MongoDB API. Note that the _context object is an instance of the previous LocationsContext class.

Use an env-var in the docker-compose.override.yml file for the MongoDB connection string

ImageWhen creating a MongoClient object, it needs a fundamental parameter which is precisely the ConnectionString parameter pointing to the right database. In the case of eShopOnContainers, the connection string can point to a local MongoDB Docker container or to a “production” Azure Cosmos DB database. That connection string comes from the environment variables defined in the docker-compose.override.yml files used when deploying with docker-compose or Visual Studio, as in the following yml code.

The ConnectionString environment variable is resolved this way: if the ESHOP_AZURE_COSMOSDB global variable is defined in the .env file with the Azure Cosmos DB connection string, it will use it to access the Azure Cosmos DB database in the cloud. If it’s not defined, it will take the mongodb://nosql.data value and use the development mongodb container.

ImageThe following code shows the .env file with the Azure Cosmos DB connection string global environment variable, as implemented in eShopOnContainers:

You should uncomment the ESHOP_AZURE_COSMOSDB line and update it with your connection string, obtained from the Azure portal, as explained in Connect a MongoDB application to Azure Cosmos DB.

ImageIf the ESHOP_AZURE_COSMOSDB global variable is empty, meaning that it is commented at the .env file, then it will use a by default MongoDB connection string pointing to the local MongoDB container deployed in eShopOnContainers which is named nosql.data and was defined at the docker-compose file, as shown in the following .yml code.

Additional resources

https://docs.microsoft.com/azure/cosmos-db/modeling-data

https://docs.microsoft.com/azure/cosmos-db/mongodb-introduction

https://docs.microsoft.com/azure/cosmos-db/create-mongodb-dotnet

https://docs.microsoft.com/azure/cosmos-db/local-emulator

https://docs.microsoft.com/azure/cosmos-db/connect-mongodb-account

https://hub.docker.com/r/microsoft/azure-cosmosdb-emulator/

https://hub.docker.com/r/_/mongo/

https://docs.microsoft.com/azure/cosmos-db/mongodb-mongochef