Skip to main content

Cosmos MongDB Hello world

Step 1 : Retrieve Mongo Connection string

Prerequisites:

  • AZ cli
  • docker
  • Instance name (Example : dbaas-romain-sandbox)
  • Key Vault instance uri provided by DBAAS team (Example: https://dbaasromainsandboxakv.vault.azure.net). Note: the name can be built with the instance name and is always following the pattern https://${SHORT_INSTANCE_NAME}akv.vault.azure.net
  • Instance ID (A 1 digit , provided by DBAAS teams. Example: 1)
        export INSTANCE_NAME="dbaas-romain-sandbox" # Replace with your instance name
export INSTANCE_ID="1"
export SHORT_INSTANCE_NAME=$(echo $INSTANCE_NAME | tr -d '-')
export MONGO_URI=$(az keyvault secret show --output tsv --query value --id https://${SHORT_INSTANCE_NAME}akv.vault.azure.net/secrets/${INSTANCE_NAME}-cos${INSTANCE_ID}-primarywriteuri)

Step 2 : Insert & Read document using CLI

This the docker sample

## Open a mongo shell
docker run -it --rm casperfrx/mongodb-shell "${MONGO_URI}"
## Switch to DB1
globaldb:PRIMARY> use db1
switched to db db1
## Hello world
db.hello()
{
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 1000,
localTime: Long("1656426186232"),
logicalSessionTimeoutMinutes: 30,
minWireVersion: 0,
maxWireVersion: 7,
readOnly: false,
tags: { region: 'East US' },
hosts: [ 'dbaas-aessed-sandbox-cos1-eastus.mongo.cosmos.azure.com:10255' ],
setName: 'globaldb',
setVersion: 1,
primary: 'dbaas-aessed-sandbox-cos1-eastus.mongo.cosmos.azure.com:10255',
me: 'dbaas-aessed-sandbox-cos1-eastus.mongo.cosmos.azure.com:10255',
connectionId: 1801329971,
ok: 1,
isWritablePrimary: true
}
## Create a collection
globaldb [primary] db1> db.createCollection("collection1")
{ ok: 1 }
## Create a document in "collection1" Collection
globaldb:PRIMARY> db.mycollection.insertOne({"message":"I'm a DBAAS User !"})
{
"acknowledged" : true,
"insertedId" : ObjectId("62b310624ae49a660335947b")
}
## Get all documents in your collection
globaldb:PRIMARY> db.collection1.find()
{ "_id" : ObjectId("62b3107c4ae49a660335947c"), "message" : "I'm a DBAAS User !" }

Appendix 1 : Install AZ Client

Please find documentation here

Appendix 2 : Connect to your database using mongo-express (Web UI)

Due to a bug in mongo-express, we have to enforce SSL Parameters with a config file :

cat << EOF > config.js
module.exports = {
mongodb: {
connectionOptions: {
ssl: true,
sslValidate: false
}
}
};
EOF

Then use a docker image to start a mongo-express, connected to your mongo instance:

docker run -it --rm -p 8081:8081   \
-e ME_CONFIG_MONGODB_URL="${MONGO_URI}" \
-v $PWD/config.js:/node_modules/mongo-express/config.js:ro \
mongo-express

open a browser on http://localhost:8081

Go to your db (db1)

img

Go to your collection img

And voila ! Here's your document created in Step1

img

Appendix 3 : Use Mongo Compass UI

  • Install following instructions here
  • Insert your ${MONGO_URI} in URI Field :

img