In the previous articles, you learnt about how to create collections, what are the features of NoSQL databases, why Cosmos DB is called a NoSQL database. Now that we have these basic pre-requisites clear, it is time to go on to work with some data creating documents on Cosmos database.
We have already created a collection called Human. To learn how to create collections, refer to the previous article, “Overview of Azure Cosmos DB collections”.
Now when we expand the Human collection, we can see the option to create a document. This is where we put in all the data required for the document.
As we go on to create a document, this is the display to us. Now, when we create the documents and provide the JSON data, it creates a unique ID for every document when we save it. See image below for reference.
After putting in the data and saving the document, it updates the document with all the id and other attributes like rid, self, etc. We have created two documents and now let’s run the queries by going to the New SQL query option on the top left.
As we see in this image, we have put the query to select all the results which have this particular pin code and it has successfully given us the documents data which has this pin code. Another important thing to note here is that ‘c’ is being used as an alias for the collection name.
We can try different things by providing different properties to any document and then running queries.
Now, suppose the query goes something like this:
In this case, it returned only one document where family name is “Anirudh”.
A good thing about this schema-free database is that you can anytime return to it with more properties and update them in the document because there is no schema management and we can update the data whenever we need to. We can also update this using code, not just manually.
We did not incur any costs while creating all these documents and implementing them using queries. This was because we are using the local emulator. However, when we need to scale out our application and distribute it globally, we would have to use the real cosmos DB account and for that we will be charged the cost required. Deploying to the cosmos DB account, though, will be very simple by changing the connection string of the emulator to that of the Cosmos DB account.
In this example, we have manually written all the data inside the documents, however, we can code and implement this using Cosmos DB which is out of scope of this blog post. However, we can also create collections and documents through code implementation.