GIANT Stories at MongoDB

Introducing the MongoDB Enterprise Operator for Kubernetes and OpenShift

Today more DevOps teams are leveraging the power of containerization, and technologies like Kubernetes and Red Hat OpenShift, to manage containerized database clusters. To support teams building cloud-native apps with Kubernetes and OpenShift, we are introducing a Kubernetes Operator (beta) that integrates with Ops Manager, the enterprise management platform for MongoDB. The operator enables a user to deploy and manage MongoDB clusters from the Kubernetes API, without having to manually configure them in Ops Manager.

With this Kubernetes integration, you can consistently and effortlessly run and deploy workloads wherever they need to be, standing up the same database configuration in different environments, all controlled with a simple, declarative configuration. Operations teams can also offer developers new services like MongoDB-as-a-Service, that could provide for them a fully managed database, alongside other products and services, managed by Kubernetes and OpenShift.

In this blog, we’ll cover the following:

  • Brief discussion on the container revolution
  • Overview of MongoDB Ops Manager
  • How to Install and configure the MongoDB Enterprise Operator for Kubernetes
  • Troubleshooting
  • Where to go for more information

The containerization movement

If you ever visited an international shipping port or drove down an interstate highway you may have seen large rectangular metal containers generally referred to as intermodal containers. These containers are designed and built using the same specifications even though the contents of these boxes can vary greatly. The consistent design not only enables these containers to freely move from ship, to rail, and to truck, they also allow this movement without unloading and reloading the cargo contents.

This same concept of a container can be applied to software applications where the application is the contents of the container along with its supporting frameworks and libraries. The container can be freely moved from one platform to another all without disturbing the application. This capability makes it easy to move an application from an on-premise datacenter server to a public cloud provider, or to quickly stand up replica environments for development, test, and production usage.

MongoDB 4.0 introduces the MongoDB Enterprise Operator for Kubernetes which enables a user to deploy and manage MongoDB clusters from the Kubernetes API, without the user having to connect directly to Ops Manager or Cloud Manager (the hosted version of Ops Manager, delivered as a service.

While MongoDB is fully supported in a containerized environment, you need to make sure that the benefits you get from containerizing the database exceed the cost of managing the configuration. As with any production database workload, these containers should use persistent storage and will require additional configuration depending on the underlying container technology used. To help facilitate the management of the containers themselves, DevOps teams are leveraging the power of orchestration technologies like Kubernetes and Red Hat OpenShift. While these technologies are great at container management, they are not aware of application specific configurations and deployment topologies such as MongoDB replica sets and sharded clusters. For this reason, Kubernetes has Custom Resources and Operators which allow third-parties to extend the Kubernetes API and enable application aware deployments.

Later in this blog you will learn how to install and get started with the MongoDB Enterprise Operator for Kubernetes. First let’s cover MongoDB Ops Manager, which is a key piece in efficient MongoDB cluster management.

Managing MongoDB

Ops Manager is an enterprise class management platform for MongoDB clusters that you run on your own infrastructure. The capabilities of Ops Manager include monitoring, alerting, disaster recovery, scaling, deploying and upgrading of replica sets and sharded clusters, and other MongoDB products, such as the BI Connector. While a thorough discussion of Ops Manager is out of scope of this blog it is important to understand the basic components that make up Ops Manager as they will be used by the Kubernetes Operator to create your deployments..

Figure 1: MongoDB Ops Manager deployment screen

A simplified Ops Manager architecture is shown in Figure 2 below. Note that there are other agents that Ops Manager uses to support features like backup but these are outside the scope of this blog and not shown. For complete information on MongoDB Ops Manager architecture see the online documentation found at the following URL:

Figure 2: Simplified Ops Manager deployment

The MongoDB HTTP Service provides a web application for administration. These pages are simply a front end to a robust set of Ops Manager REST APIs that are hosted in the Ops Manager HTTP Service. It is through these REST APIs that the Kubernetes Operator will interact with Ops Manager.

MongoDB Automation Agent

With a typical Ops Manager deployment there are many management options including upgrading the cluster to a different version, adding secondaries to an existing replica set and converting an existing replica set into a sharded cluster. So how does Ops Manager go about upgrading each node of a cluster or spinning up new MongoD instances? It does this by relying on a locally installed service called the Ops Manager Automation Agent which runs on every single MongoDB node in the cluster. This lightweight service is available on multiple operating systems so regardless if your MongoDB nodes are running in a Linux Container or Windows Server virtual machine or your on-prem PowerPC Server, there is an Automation Agent available for that platform. The Automation Agents receive instructions from Ops Manager REST APIs to perform work on the cluster node.

MongoDB Monitoring Agent

When Ops Manager shows statistics such as database size and inserts per second it is receiving this telemetry from the individual nodes running MongoDB. Ops Manager relies on the Monitoring Agent to connect to your MongoDB processes, collect data about the state of your deployment, then send that data to Ops Manager. There can be one or more Monitoring Agents deployed in your infrastructure for reliability but only one primary agent per Ops Manager Project is collecting data. Ops Manager is all about automation and as soon as you have the automation agent deployed, other supporting agents like the Monitoring agent are deployed for you. In the scenario where the Kubernetes Operator has issued a command to deploy a new MongoDB cluster in a new project, Ops Manager will take care of deploying the monitoring agent into the containers running your new MongoDB cluster.

Getting started with MongoDB Enterprise Operator for Kubernetes

Ops Manager is an integral part of automating a MongoDB cluster with Kubernetes. To get started you will need access to an Ops Manager 4.0+ environment or MongoDB Cloud Manager.

The MongoDB Enterprise Operator for Kubernetes is compatible with Kubernetes v1.9 and above. It also has been tested with Openshift version 3.9. You will need access to a Kubernetes environment. If you do not have access to a Kubernetes environment, or just want to stand up a test environment, you can use minikube which deploys a local single node Kubernetes cluster on your machine. For additional information and setup instructions check out the following URL:

The following sections will cover the three step installation and configuration of the MongoDB Enterprise Operator for Kubernetes. The order of installation will be as follows:

  • Step 1: Installing the MongoDB Enterprise Operator via a helm or yaml file
  • Step 2: Creating and applying a Kubernetes ConfigMap file
  • Step 3: Create the Kubernetes secret object which will store the Ops Manager API Key

Step 1: Installing MongoDB Enterprise Operator for Kubernetes

To install the MongoDB Enterprise Operator for Kubernetes you can use helm, the Kubernetes package manager, or pass a yaml file to kubectl. The instructions for both of these methods is as follows, pick one and continue to step 2.

To install the operator via Helm:

To install with Helm you will first need to clone the public repo

Change directories into the local copy and run the following command on the command line:

helm install helm_chart/ --name mongodb-enterprise

To install the operator via a yaml file:

Run the following command from the command line:

kubectl apply -f

At this point the MongoDB Enterprise Operator for Kubernetes is installed and now needs to be configured. First, we must create and apply a Kubernetes ConfigMap file. A Kubernetes ConfigMap file holds key-value pairs of configuration data that can be consumed in pods or used to store configuration data. In this use case the ConfigMap file will store configuration information about the Ops Manager deployment we want to use.

Step 2: Creating the Kubernetes ConfigMap file

For the Kubernetes Operator to know what Ops Manager you want to use you will need to obtain some properties from the Ops Manager console and create a ConfigMap file. These properties are as follows:

Base Url - The URL of your Ops Manager or Cloud Manager.

Project Id - The id of an Ops Manager Project which the Kubernetes Operator will deploy into.

User - An existing Ops Manager username

Public API Key - Used by the Kubernetes Operator to connect to the Ops Manager REST API endpoint

If you already know how to obtain these follows copy them down and proceed to Step 3.

Base Url

The Base Uri is the URL of your Ops Manager or Cloud Manager.

Note: If you are using Cloud Manager the Base Url is, “

To obtain the Base Url in Ops Manager copy the Url used to connect to your Ops Manager server from your browser's navigation bar. It should be something similar to http://servername:8080. You can also perform the following:

Login to Ops Manager and click on the Admin button. Next select the “Ops Manager Config” menu item. You will be presented with a screen similar to the figure below:

Figure 3: Ops Manager Config page

Copy down the value displayed in the URL To Access Ops Manager box. Note: If you don’t have access to the Admin drop down you will have to copy the Url used to connect to your Ops Manager server from your browser's navigation bar.

Project Id

The Project Id is the id of an Ops Manager Project which the Kubernetes Operator will deploy into.

An Ops Manager Project is a logical organization of MongoDB clusters and also provides a security boundary. One or more Projects are apart of an Ops Manager Organization. If you need to create an Organization click on your user name at the upper right side of the screen and select, “Organizations”. Next click on the “+ New Organization” button and provide a name for your Organization. Once you have an Organization you can create a Project.

Figure 4: Ops Manager Organizations page

To create a new Project, click on your Organization name. This will bring you to the Projects page and from here click on the “+ New Project” button and provide a unique name for your Project. If you are not an Ops Manager administrator you may not have this option and will have to ask your administrator to create a Project.

Once the Project is created or if you already have a Project created on your behalf by an administrator you can obtain the Project Id by clicking on the Settings menu option as shown in the Figure below.

Figure 5: Project Settings page

Copy the Project ID.


The User is an existing Ops Manager username

To see the list of Ops Manager users return to the Project and click on the “Users & Teams” menu. You can use any Ops Manager user who has at least Project Owner access. If you’d like to create another username click on the “Add Users & Team” button as shown in Figure 6.

Figure 6: Users & Teams page

Copy down the email of the user you would like the Kubernetes Operator to use when connecting to Ops Manager.

Public API Key

The Ops Manager API Key is used by the Kubernetes Operator to connect to the Ops Manager REST API endpoint. You can create a API Key by clicking on your username on the upper right hand corner of the Ops Manager console and selecting, “Account” from the drop down menu. This will open the Account Settings page as shown in Figure 7.

Figure 7: Public API Access page

Click on the “Public API Access” tab. To create a new API key click on the “Generate” button and provide a description. Upon completion you will receive an API key as shown in Figure 8.

Figure 8: Confirm API Key dialog

Be sure to copy the API Key as it will be used later as a value in a configuration file. It is important to copy this value while the dialog is up since you can not read it back once you close the dialog. If you missed writing the value down you will need to delete the API Key and create a new one.

Note: If you are using MongoDB Cloud Manager or have Ops Manager deployed in a secured network you may need to whitelist the IP range of your Kubernetes cluster so that the Operator can make requests to Ops Manager using this API Key.

Now that we have acquired the necessary Ops Manager configuration information we need to create a Kubernetes ConfigMap file for the Kubernetes Project. To do this use a text editor of your choice and create the following yaml file, substituting the bold placeholders for the values you obtained in the Ops Manager console. For sample purposes we can call this file “my-project.yaml”.

apiVersion: v1
kind: ConfigMap
  name:<<Name i.e. name of OpsManager Project>>
  namespace: mongodb
  projectId:<<Project ID>>
  baseUrl: <<OpsManager URL>>

Figure 9: Sample ConfigMap file

Note: The format of the ConfigMap file may change over time as features and capabilities get added to the Operator. Be sure to check with the MongoDB documentation if you are having problems submitting the ConfigMap file.

Once you create this file you can apply the ConfigMap to Kubernetes using the following command:

kubectl apply -f my-project.yaml

Step 3: Creating the Kubernetes Secret

For a user to be able to create or update objects in an Ops Manager Project they need a Public API Key. Earlier in this section we created a new API Key and you hopefully wrote it down. This API Key will be held by Kubernetes as a Secret object.

You can create this Secret with the following command:

kubectl -n mongodb create secret generic <<Name of credentials>> --from-literal="user=<<User>>" --from-literal="publicApiKey=<<public-api-key>>"

Make sure you replace the User and Public API key values with those you obtained from your Ops Manager console. You can pick any name for the credentials – just make a note of it as you will need it later when you start creating MongoDB clusters.

Now we're ready to start deploying MongoDB Clusters!

Deploying a MongoDB Replica Set

Kubernetes can deploy a MongoDB standalone, replica set or a sharded cluster. To deploy a 3 node replica set create the following yaml file:

kind: MongoDbReplicaSet
  name: <<Name of your new MongoDB replica set>>
  namespace: mongodb
  members: 3
  version: 3.6.5

  persistent: false

  project: <<Name value specified in of ConfigMap file>>
  credentials: <<Name of credentials secret>>
Figure 10: simple-rs.yaml file describing a three node replica set

The name of your new cluster can be any name you chose. The name of the OpsManager Project config map and the name of credentials secret were defined previously.

To submit the request for Kubernetes to create this cluster simply pass the name of the yaml file you created to the following kubectl command:

kubectl apply -f simple-rs.yaml

After a few minutes your new cluster will show up in Ops Manager as shown in Figure 11.

Figure 11: Servers tab of the Deployment page in Ops Manager

Notice that Ops Manager installed not only the Automation Agents on these three containers running MongoDB, it also installed Monitoring Agent and Backup Agents.

A word on persistent storage

What good would a database be if anytime the container died your data went to the grave as well? Probably not a good situation and maybe one where tuning up the resumé might be a good thing to do as well. Up until recently, the lack of persistent storage and consistent DNS mappings were major issues with running databases within containers. Fortunately, recent work in the Kubernetes ecosystem has addressed this concern and new features like PersistentVolumes and StatefulSets have emerged allowing you to deploy databases like MongoDB without worrying about losing data because of hardware failure or the container moved elsewhere in your datacenter. Additional configuration of the storage is required on the Kubernetes cluster before you can deploy a MongoDB Cluster that uses persistent storage. In Kubernetes there are two types of persistent volumes: static and dynamic. The Kubernetes Operator can provision MongoDB objects (i.e. standalone, replica set and sharded clusters) using either type.

Connecting your application

Connecting to MongoDB deployments in Kubernetes is no different than other deployment topologies. However, it is likely that you'll need to address the network specifics of your Kubernetes configuration. To abstract the deployment specific information such as hostnames and ports of your MongoDB deployment, the Kubernetes Enterprise Operator for Kubernetes uses Kubernetes Services.


Each MongoDB deployment type will have two Kubernetes services generated automatically during provisioning. For example, suppose we have a single 3 node replica set called "my-replica-set", then you can enumerate the services using the following statement:

kubectl get all -n mongodb --selector=app=my-replica-set-svc

This statement yields the following results:

NAME                   READY     STATUS    RESTARTS   AGE
pod/my-replica-set-0   1/1       Running   0          29m
pod/my-replica-set-1   1/1       Running   0          29m
pod/my-replica-set-2   1/1       Running   0          29m

NAME                                  TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)           AGE
service/my-replica-set-svc            ClusterIP   None             <none>        27017/TCP         29m
service/my-replica-set-svc-external   NodePort   <none>        27017:30057/TCP   29m

NAME                              DESIRED   CURRENT   AGE
statefulset.apps/my-replica-set   3         3         29m

Note the appended string "-svc" to the name of the replica set.

The service with "-external" is a NodePort - which means it's exposed to the overall cluster DNS name on port 30057.

Note: If you are using Minikube you can obtain the IP address of the running replica set by issuing the following:

minikube service list

In our example which used minikube the result set contained the following information: mongodb my-replica-set-svc-external

Now that we know the IP of our MongoDB cluster we can connect using the Mongo Shell or whatever application or tool you would like to use.

Basic Troubleshooting

If you are having problems submitting a deployment you should read the logs. Issues like authentication issues and other common problems can be easily detected in the log files. You can view the MongoDB Enterprise Operator for Kubernetes log files via the following command:

kubectl logs -f deployment/mongodb-enterprise-operator -n mongodb

You can also use kubectl to see the logs of the database pods. The main container processes is continually tailing the Automation Agent logs and can be seen with the following statement:

kubectl logs <<name of pod>> -n mongodb

Note: You can enumerate the list of pods using

kubectl get pods -n mongodb

Another common troubleshooting technique is to shell into one of the containers running MongoDB. Here you can use common Linux tools to view the processes, troubleshoot, or even check mongo shell connections (sometimes helpful in diagnosing network issues).

kubectl exec -it <<name of pod>> -n mongodb -- /bin/bash

An example output of this command is as follows:

mongodb      1     0  0 16:23 ?        00:00:00 /bin/sh -c supervisord -c /mongo
mongodb      6     1  0 16:23 ?        00:00:01 /usr/bin/python /usr/bin/supervi
mongodb      9     6  0 16:23 ?        00:00:00 bash /mongodb-automation/files/a
mongodb     25     9  0 16:23 ?        00:00:00 tail -n 1000 -F /var/log/mongodb
mongodb     26     1  4 16:23 ?        00:04:17 /mongodb-automation/files/mongod
mongodb     45     1  0 16:23 ?        00:00:01 /var/lib/mongodb-mms-automation/
mongodb     56     1  0 16:23 ?        00:00:44 /var/lib/mongodb-mms-automation/
mongodb     76     1  1 16:23 ?        00:01:23 /var/lib/mongodb-mms-automation/
mongodb   8435     0  0 18:07 pts/0    00:00:00 /bin/bash

From inside the container we can make a connection to the local MongoDB node easily by running the mongo shell via the following command:

/var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.6.5/bin/mongo --port 27017

Note: The version of the automation agent may be different than 3.6.5, be sure to check the directory path

Where to go for more information

More information will be available on the MongoDB documentation website in the near future. Until then check out these resources for more information:

Slack: #enterprise-kubernetes

Sign up @


To see all MongoDB operations best practices, download our whitepaper:

Getting Started with Python and MongoDB

You can get started with MongoDB and your favorite programming language by leveraging one of its drivers, many of which are maintained by MongoDB engineers, and others which are maintained by members of the community. MongoDB has a native Python driver, PyMongo, and a team of Driver engineers dedicated to making the driver fit to the Python community’s needs.

In this article, which is aimed at Python developers who are new to MongoDB, you will learn how to do the following:

  • Create a free hosted MongoDB database using MongoDB Atlas
  • Install PyMongo, the Python Driver
  • Connect to MongoDB
  • Explore MongoDB Collections and Documents
  • Perform basic Create, Retrieve, Update and Delete (CRUD) operations using PyMongo

Let’s get started!

You can start working immediately with MongoDB by using a free MongoDB cluster via MongoDB Atlas. MongoDB Atlas is a hosted database service that allows you to choose your database size and get a connection string! If you are interested in using the free tier follow the instructions in the Appendix section at the end of this article.

Install the Python Driver

For this article we will install the Python driver called, “PyMongo”.

Although there are other drivers written by the community, PyMongo is the official Python driver for MongoDB. For a detailed documentation on the driver check out the documentation here.

The easiest way to install the driver is through the pip package management system. Execute the following on a command line:

python -m pip install pymongo

Note: If you are using the Atlas M0 (Free Tier) cluster, you must use Python 2.7.9+ and use a Python 3.4 or newer. You can check which version of Python and PyMongo you have installed by issuing “python --version” and “pip list” commands respectively.

For variations of driver installation check out the complete documentation:

Once PyMongo is installed we can write our first application that will return information about the MongoDB server. In your Python development environment or from a text editor enter the following code.

from pymongo import MongoClient
# pprint library is used to make the output look more pretty
from pprint import pprint
# connect to MongoDB, change the << MONGODB URL >> to reflect your own connection string
client = MongoClient(<<MONGODB URL>>)
# Issue the serverStatus command and print the results

Replace the “<>” with your connection string to MongoDB. Save this file as “” and run it from the command line via, “python”

An example output appears as follows:

{u'asserts': {u'msg': 0,
              u'regular': 0,
              u'rollovers': 0,
              u'user': 0,
              u'warning': 0},
 u'connections': {u'available': 96, u'current': 4, u'totalCreated': 174L},
 u'extra_info': {u'note': u'fields vary by platform', u'page_faults': 0},
 u'host': u'',
 u'localTime': datetime.datetime(2017, 4, 4, 0, 18, 45, 616000),

Note that the ‘u’ character comes from the python output and it means that the strings are stored in unicode. This example also uses the pprint library which is not related to MongoDB but is used here only to make the output structured and visually appealing from a console.

In this example we are connecting to our MongoDB instance and issuing the “db.serverStatus()” command (reference). This command returns information about our MongoDB instance and is used in this example as a way to execute a command against MongoDB.

If your application runs successfully, you are ready to continue!

Exploring Collections and Documents

MongoDB stores data in documents. Documents are not like Microsoft Word or Adode PDF documents but rather JSON documents based on the JSON specification.
An example of a JSON document would be as follows:

![JSON document example](
Figure 1: Sample document

Notice that documents are not just key/value pairs but can include arrays and subdocuments. The data itself can be different data types like geospatial, decimal, and ISODate to name a few. Internally MongoDB stores a binary representation of JSON known as BSON. This allows MongoDB to provide data types like decimal that are not defined in the JSON specification. For more information on the BSON spec check out the following URL:

A collection in MongoDB is a container for documents. A database is the container for collections. This grouping is similar to relational databases and is pictured below:



Relational concept MongoDB equivalent
Database Database

There are many advantages to storing data in documents. While a deeper discussion is out of the scope of this article, some of the advantages like dynamic, flexible schema, and the ability to store arrays can be seen from our simple Python scripts. For more information on MongoDB document structure take a look at the online documentation at the following URL:

Let’s take a look at how to perform basic CRUD operations on documents in MongoDB using PyMongo.

Performing basic CRUD operations using PyMongo

To establish a connection to MongoDB with PyMongo you use the MongoClient class.

from pymongo import MongoClient
client = MongoClient('<<MongoDB URL>>’)

The “<<MongoDB URL>>”is a placeholder for the connection string to MongoDB. See the connection string documentation for detail information on how to create your MongoDB connection string. If you are using Atlas for your MongoDB database, refer to the “testing your connection” section for more information on obtaining the connection string for MongoDB Atlas.

We can now create a database object referencing a new database, called “business”, as follows:

db =

Once we create this object we can perform our CRUD operations. Since we want something useful to query let’s start by building a sample data generator application.

Generating sample data code example

Create a new file called using your development tool or command line text editor and copy the following code:

from pymongo import MongoClient
from random import randint
#Step 1: Connect to MongoDB - Note: Change connection string as needed
client = MongoClient(port=27017)
#Step 2: Create sample data
names = ['Kitchen','Animal','State', 'Tastey', 'Big','City','Fish', 'Pizza','Goat', 'Salty','Sandwich','Lazy', 'Fun']
company_type = ['LLC','Inc','Company','Corporation']
company_cuisine = ['Pizza', 'Bar Food', 'Fast Food', 'Italian', 'Mexican', 'American', 'Sushi Bar', 'Vegetarian']
for x in xrange(1, 501):
    business = {
        'name' : names[randint(0, (len(names)-1))] + ' ' + names[randint(0, (len(names)-1))]  + ' ' + company_type[randint(0, (len(company_type)-1))],
        'rating' : randint(1, 5),
        'cuisine' : company_cuisine[randint(0, (len(company_cuisine)-1))] 
    #Step 3: Insert business object directly into MongoDB via isnert_one
    #Step 4: Print to the console the ObjectID of the new document
    print('Created {0} of 100 as {1}'.format(x,result.inserted_id))
#Step 5: Tell us that you are done
print('finished creating 100 business reviews')

Be sure to change the MongoDB client connection URL to one that points to your MongoDB database instance. Once you run this application, 500 randomly named businesses with their corresponding ratings will be created in the MongoDB database called, “business”. All of these businesses are created in a single collection called, “reviews”. Notice that we do not have to explicitly create a database beforehand in order to use it. This is different from other databases that require statements like, “CREATE DATABASE” to be performed first.

The command that inserts data into MongoDB in this example is the insert_one() function. A bit self-explanatory, insert_one will insert one document into MongoDB. The result set will return the single ObjectID that was created. This is one of a few methods that insert data. If you wanted to insert multiple documents in one call you can use the insert_many function. In addition to an acknowledgement of the insertion, the result set for insert_many will include a list of the ObjectIDs that were created. For more information on insert_many see the documentation located here.

For details on the result set of insert_many check out this section of documentation as well.

We are now ready to explore querying and managing data in MongoDB using Python. To guide this exploration we will create another application that will manage our business reviews.

Exploring business review data

Now that we have a good set of data in our database let’s query for some results using PyMongo.

In MongoDB the find_one command is used to query for a single document much like select statements are used in relational databases. To use the find_one command in PyMongo we pass a Python dictionary that specifies the search criteria. For example, let’s find a single business with a review score of 5 by passing the dictionary, “{ ‘rating’ : 5 } “.

fivestar ={'rating': 5})

The result will contain data similar to the following:

{u'rating': 5,
 u'_id': ObjectId('58e65383ea0b650c867ef195'),
 u'name': u'Fish Salty Corporation', 
u'cuisine': u'Sushi Bar'}

Given we created 500 sample pieces of data there is more than one business with rating 5. The find_one method is just one in a series of find statements that support querying MongoDB data. Another statement, called “find”, will return a cursor over all documents that match the search criteria. These cursors also support methods like count() which returns the number of results in the query. To find the total count of businesses that are rated with a 5 we can use the count() method as follows:

fivestarcount ={'rating': 5}).count()

Your results may vary since the data was randomly generated but in a test run the value of 103 was returned.

MongoDB can easily perform these straightforward queries. However, consider the scenario where you want to sum the occurrence of each rating across the entire data set. In MongoDB you could create 5 separate find queries, execute them and present the results, or you could simply issue a single query using the MongoDB aggregation pipeline as follows:

from pymongo import MongoClient
# Connect to the MongoDB, change the connection string per your MongoDB environment
client = MongoClient(port=27017)
# Set the db object to point to the business database
# Showcasing the count() method of find, count the total number of 5 ratings 
print('The number of 5 star reviews:')
fivestarcount ={'rating': 5}).count()
# Not let's use the aggregation framework to sum the occurrence of each rating across the entire data set
print('\nThe sum of each rating occurance across all data grouped by rating ')
# The Aggregation Pipeline is defined as an array of different operations
# The first stage in this pipe is to group data
{ '$group':
    { '_id': "$rating",
     "count" : 
                 { '$sum' :1 }
# The second stage in this pipe is to sort the data
{"$sort":  { "_id":1}
# Close the array with the ] tag             
] )
# Print the result
for group in stargroup:

A deep dive into the aggregation framework is out of scope of this article, however, if you are interested in learning more about it check out the following URL:

Updating data with PyMongo

Similar to insert_one and insert_many there exists functions to help you update your MongoDB data including update_one, update_many and replace_one. The update_one method will update a single document based on a query that matches a document. For example, let’s assume that our business review application now has the ability for users to “like” a business. To illustrate updating a document with this new “likes” field, let’s first take a look at what an existing document looks like from our previous application’s insertion into MongoDB. Next, let’s update the document and requery the document and see the change.

from pymongo import MongoClient
#include pprint for readabillity of the 
from pprint import pprint

#change the MongoClient connection string to your MongoDB database instance
client = MongoClient(port=27020)

ASingleReview ={})
print('A sample document:')

result ={'_id' : ASingleReview.get('_id') }, {'$inc': {'likes': 1}})
print('Number of documents modified : ' + str(result.modified_count))

UpdatedDocument ={'_id':ASingleReview.get('_id')})
print('The updated document:')

When running the sample code above you may see results similar to the following:

A sample document:
{'_id': ObjectId('58eba417ea0b6523b0fded4f'),
 'cuisine': 'Pizza',
 'name': 'Kitchen Goat Corporation',
 'rating': 1}

Number of documents modified : 1

The updated document:
{'_id': ObjectId('58eba417ea0b6523b0fded4f'),
 'cuisine': 'Pizza',
 'likes': 1,
 'name': 'Kitchen Goat Corporation',
 'rating': 1}

Notice that the original document did not have the “likes” field and an update allowed us to easily add the field to the document. This ability to dynamically add keys without the hassle of costly Alter_Table statements is the power of MongoDB’s flexible data model. It makes rapid application development a reality.

If you wanted to update all the fields of the document and keep the same ObjectID you will want to use the replace_one function. For more details on replace_one check out the pymongo documentation here.

The update functions also support an option called, “upsert”. With upsert you can tell MongoDB to create a new document if the document you are trying to update does not exist.

Deleting documents

Much like the other command discussed so far the delete_one and delete_many command takes a query that matches the document to delete as the first parameter. For example, if you wanted to delete all documents in the reviews collection where the category was “Bar Food” issue the following:

result = db.restaurants.delete_many({“category”: “Bar Food“})

If you are deleting a large number of documents it may be more efficient to drop the collection instead of deleting all the documents.

Where to go next

There are lots of options when it comes to learning about MongoDB and Python. MongoDB University is a great place to start and learn about administration, development and other topics such as analytics with MongoDB. One course in particular is MongoDB for Developers (Python). This course covers the topics of this article in much more depth including a discussion on the MongoDB aggregation framework. For more information go to the following URL:

Appendix: Creating a free tier MongoDB Atlas database

MongoDB Atlas is a hosted database service that allows you to choose your database size and get a connection string! Follow the steps below to start using your free

Build your cluster for free

Follow the below steps to create a free MongoDB database:

  1. Go to the following URL:
  2. Click the “Start Free” button
  3. Fill out the form to create an account. You will use this information to later login and manage your MongoDB.

Once you fill out the form, the website will create your account and you will be presented with the “Build Your New Cluster” pop up as shown in Figure 1.

!["Build your new cluster"](

To use the free tier scroll down and select, “M0”. When you do this the regions panel will be disabled. The free tier has some restrictions with the ability to select a region being one of them and your database size will be limited to 512MB of storage. Given that, when you are ready to use MongoDB for more than just some simple operations you can easily create another instance by choosing a size from the “Instance Size” list. Before you click “Confirm & Deploy” scroll down the page and notice the additional options shown in Figure 2.

![Additional options in Build New Cluster dialog](

From the “Build Your New Cluster” pop up you can see that there are other options available including choosing a 3, 5 or 7 node replica set and up to a 12 shard cluster. Note that the free tier does not allow you to chose anything more than the 3 node cluster, but if you move into other sizes these options will become available. At this point we are almost ready; the last thing to address is the admin username and password. You may also choose to have a random password generated for you by clicking the “Autogenerate Secure Password” button. Finally, click the “Confirm & Deploy” button to create your Atlas cluster. Setting up your IP Whitelist

While Atlas is creating your database you will need to define which IP’s are allowed access to your new database since MongoDB Atlas does not allow access from the internet by default. This list of granted IP addresses is called the “IP Whitelist”. To add the IP of your machine to this list click on the “Security” tab, then “IP Whitelist” then click the “+ ADD IP ADDRESS” button. This will pop up another dialog shown in Figure 3 below. You can click the “Add current IP Address” button to add your IP or provide a specific IP address or enable access to the world by not restricting IPs at all (not a fantastic idea but there in case you have no other choice and need to allow authentication from any IP).

Add whitelist entry

Once you have filled out this dialog click “Confirm” and this will update the firewall settings on your MongoDB Atlas cluster. Next, click on the “Clusters” tab and you should see your new MongoDB database ready for action!

!["Cluster0" ready for action](

Testing your connection

We want to make sure the MongoDB database is accessible from our development box before we start typing in code. A quick way to test is to make a connection using the Mongo Shell command line tool. Be sure to have your MongoDB connection information available. If you are using MongoDB Atlas you can obtain the connection information by clicking on the “Connect” button on the Clusters tab as shown in Figure 5.

![Connect button of the MongoDB Atlas cluster](

The Connect button will launch a dialog that provides connection information. At the bottom of this dialog you will see a prepared command line ready for you to simply copy and paste in a command prompt.

![Connect with Mongo Shell section of the Connect dialog](

Note that if you copy the connection text as-is you will have to replace with the password for the admin user, and with the name of the database to which you wish to connect.

The command text that comes from this dialog is lengthy. For clarity, let’s take a look at each of the parameters individually.

 --authenticationDatabase admin 
--username myadmin 
--password S$meComPLeX1!

The first parameter is a string containing the list of all the nodes in our cluster including the definition of a replica set called, “Cluster0-shard-0”. The next parameter, “--authenticationDatabase” tells which database contains the user we want to authenticate. The “--ssl” forces the connection to be encrypted via SSL/TLS protocol. Finally we provide the username and password, and we are connected! Note that if you are not using MongoDB Atlas, your MongoDB deployment may not have security enabled or require SSL. Thus, connecting to it could be as simple as typing “mongo” in the command prompt.

You are now ready to use MongoDB!

If you're interested in learning everything you need to know to get started building a MongoDB-based app you can sign up for one of our free online MongoDB University courses.

Providing Least Privileged Data Access in MongoDB

Robert Walters
January 13, 2017

Many years ago I took a semester off from college and worked as a software developer intern for a consulting company. To protect the innocent I won't reveal the names and you can't find any information about this time on my LinkedIn profile so don't bother checking. The reason I mentioned this point in my life is my job at that consulting company was working with a major manufacturer on their financial reporting system. My job you ask? To write the security component. Yes, I as the intern was given the responsibility of writing the component to handle the authentication and authorization of the entire application. After all, security is an afterthought of the software development process.

Fast forward a few decades and look at how times have changed! I don't believe that consulting company is around anymore and I hope that the application they wrote has been upgraded a few times since my work on it. Today threats are everywhere and quality software vendors put security code reviews as a release criteria to ship their product. The team behind MongoDB, the world's fastest growing database is no different in their approach to security, and this is why you see security enhancements like read-only views in their latest MongoDB 3.4 release.

A Word from our Sponsor!

Of course, no article on security is complete without reminding readers of one critical fact – before you go into production with your new MongoDB-based application, enable access control! Its quick and straightforward - the MongoDB Security Checklist steps you through what you need to do

What are Read-only Views?

Read-only views (ROV) are a similar concept to table views found in relational databases. They enable administrators to define a query that is materialized at runtime. ROVs do not store data and are considered first class objects in MongoDB. Being first class objects allows administrators to define permissions on who can access the views. ROVs become a separation layer between the data itself and the user. This is one of the biggest benefits of the feature: Users accessing the view do not need access to the underlying data the view is referencing. In addition it is important to note that since the view does not store data, as the source data changes so does the results of the view, so developers don’t need to concern themselves with working around the issues imposed by eventual consistency, such as returning stale or deleted data.

Why are read-only views (ROV) and security mentioned in the same sentence?

From a security standpoint think of the scenario where you have a customer service web application that queries for customer information. The database the application is using contains more information than the customer service representative needs such as social security numbers, and other sensitive information. At first glance you may think this is an easy problem to solve, just make sure the queries that the web application is submitting to the database does not request those sensitive fields. On paper this works and if everyone were honest the world would be a peaceful place and my article would be very short. However, there are some people that want to exploit this flawed assumption.

Imagine that we stick with this design where the credentials that the web application is using to connect to the database has direct access to the appropriate tables/collections. If an attacker compromised our web application they could be allowed to make a connection to our database. Once connected they could make their own ad-hoc queries and return the sensitive information that is contained in the database since the web application credentials has the appropriate access to the data. To mitigate this security issue there are different solutions depending on the database platform you are using. For example, within MongoDB you could have a job that copies just the key pieces of data into a new collection and give the web application just access to that collection, but this introduces moving parts in the application and the database. In the end you will find that read-only views make these work arounds redundant. At a high level our security issue can be mitigated using MongoDB's ROVs as follows:

  • Create a view that contains an aggregation query on the data you wish to obtain
  • Create a role that has "find" permission on the view
  • Create or grant a user access to the role

The following is a step by step example on leveraging ROVs as a separation between a user and the data.

Example: Securing a customer service web application using MongoDB's Read-only Views To walk through this example you will need a MongoDB instance available. To download the latest version of MongoDB go to

For help on installing MongoDB go to

For purposes of this demonstration the MongoDB instance does not need to be configured in any special way, such as configuring a replica set or enabling sharding. A simple out of the box instance of MongoDB running is acceptable. For this example I created a new folder called, "ROVExample" and started the mongod process which will use the default port of 27017. If you wish to use a different port you may specify it with the "--port" parameter.

Command Prompt> mkdir ROVExample

Command Prompt> mongod --dbpath ROVExample

2017-01-04T09:32:23.190-0500 I INDEX    [initandlisten] build index done.  scanned 0 total records. 0 secs
2017-01-04T09:32:23.190-0500 I COMMAND  [initandlisten] setting featureCompatibilityVersion to 3.4
2017-01-04T09:32:23.191-0500 I NETWORK  [thread1] waiting for connections on port 27017

At this point we have an instance of MongoDB running and waiting for our connections. Now we want to enable MongoDB to use authentication via traditional usernames and passwords. There are other authentication mechanisms such as X.509 certificates and leveraging LDAP. For more information on these other mechanisms check out the docs on MongoDB authentication. . To enable authentication with MongoDB we must first connect to our MongoDB instance and create an administrator user. In the below snippet we are connecting to our MongoDB instance via the Mongo Shell command line tool. Next we are switching to the ADMIN database and using the db.createUser() function to create a user that is an administrator.

Command Prompt> mongo

(mongod-3.4.0) test> use admin
switched to db admin

(mongod-3.4.0) admin> db.createUser(
    user: "theadmin",
    pwd: "pass@word1",
    roles: [ { role: "root", db: "admin" } ]

Upon successful execution of the command you will get a message like this one:

Successfully added user: {
  "user": "theadmin",
  "roles": [
      "role": "root",
      "db": "admin"

Now that we have created the admin account we need to stop the MongoDB service and restart it with the "--auth" switch which tells MongoDB to require authentication. Note, if we were running a replica set, we could instead use a rolling restart as we enable authentication across the cluster, thus avoiding any service interruption

Command Prompt> mongod --dbpath ROVExample --auth
2017-01-04T09:52:32.713-0500 I CONTROL  [initandlisten] options: { security: { authorization: "enabled" }, storage: { dbPath: "ROVExample" } }
2017-01-04T09:52:33.355-0500 I NETWORK  [thread1] waiting for connections on port 27017

Now log in to MongoDB with the account we just created. We do this by passing the credentials and a parameter called, "--authenticationDatabase" which tells MongoDB where the user credentials for the given user are stored. Since we created the user in the admin database we will connect to MongoDB using the shell as follows:

Command Prompt>mongo --authenticationDatabase=admin -u theadmin -p pass@word1

MongoDB shell version v3.4.0
connecting to: mongodb:
MongoDB Enterprise > 

We are now ready to create some sample data to use with this demonstration. A complete discussion of enabling authentication in MongoDB is available in the online documentation.

Side Note: When you supply a password on the command line for any application, including our example above, remember that anything you type is available in a command line history. For example, if you're on a linux platform, just type, "history" on the command line to see. If you are paranoid or connecting to your production database try launching the shell with just the "mongo --authenticationDatabase=admin" then once connected use the db.auth() command as follows:

MongoDB Enterprise > use admin
switched to db admin

MongoDB Enterprise > db.auth('root','pass@word1')
MacBook-Pro-121(mongod-3.4.0) admin> 

Inserting Sample Data

In this example we will be inserting a simple document that contains both fields a customer service web application might use (i.e. first name, last name, and address) and some data that is related to a customer but is sensitive (i.e. social security number, date of birth, etc).

MongoDB Enterprise > use FooBarFinancial

switched to db FooBarFinancial

MongoDB Enterprise > db.Customers.insert(
 { first_name: "Rob", last_name: "Walters", 
   SSN: "123-45-6789", DOB: "01/01/1996",
   address_line_1: "123 Main St.", city: "Boston", state: "MA" } )

(Yes I am 21, at least that's what I keep telling myself.. )

Side Note: The best practice is you only want to give users the least permission they need to do their job. In a production environment we may want to craft special custom roles that only do the tasks the users need. In some cases like this one where we are in a development/test environment I am ok with using a superuser role like ROOT. There are a few roles that are considered "superusers". These roles can elevate themselves and special care should be taken when using them. Be sure to audit your MongoDB instance to keep honest people honest. For more information on the superuser roles see the build-in roles section of the MongoDB online documentation.

At this point we have created the "FooBarFinancial" database and added a document to the Customers collection. If you perform a simple Find statement you can verify as follows:

MongoDB Enterprise > db.Customers.find()
  "_id": ObjectId("586d1b6680ca46840069e50b"),
  "first_name": "Rob",
  "last_name": "Walters",
  "SSN": "123-45-6789",
  "DOB": "01/01/1996",
  "address_line_1": "123 Main St.",
  "city": "Boston",
  "state": "MA"

Side Note: If you are not familiar with MongoDB you may notice a new field called, "id" that we didn't add when we created the document. In MongoDB every document needs to have a unique field called, "id". Although you can specifically provide one, if you don't you will get one created for you in the form of what looks like a Globally Unique ID (GUID). This GUID contains a timestamp of the creation time. You can see this yourself by simply copying and pasting in the ObjectId value and a .getTimestamp() command as follows:

MongoDB Enterprise > ObjectId("586d1b6680ca46840069e50b").getTimestamp()*


Creating the view

At this point we are ready for our first step in the solution, configuring the view. Read-only Views (ROV) as mentioned previously are materialized at run-time and thus store no actual data. To create one we will go to the "FooBarFinancial" database and create the view as follows:

MongoDB Enterprise > db.createView("ViewCustomers", "Customers",
   { $project:
      { first_name: 1,
        last_name: 1, 
        address_line1: 1,
        city: 1, 
        state: 1 
 ] )

The first argument is the name of the view, followed by the collection the view will be using, followed by the aggregation query we are looking to execute to retrieve our data. In this example we have a very simple aggregation query that just uses $project to return the 5 keys. Note that the "1" value means include this column, we could have also listed the other keys and said, "0" which means do not include. For additional reading on the aggregation pipeline please check out the following URL:

Once we created this view if you issue a query in the MongoDB shell (show collections) you will see that two new collections were created in the FooBarFinancial database: system.views and ViewCustomers. System.views stores the metadata for the views defined in the collection and ViewCustomers is our read-only view presented to us as a collection. Why does my ROV appear as a collection? This allows us as administrators to define access on this view.

Creating user-defined roles

Rather than give a specific user specific access to a specific resource, we want to avoid management headaches by grouping access privileges into roles. We can then grant access to these roles to the users themselves. Let's create the "CustomerServiceQuery" role and give it "find" permissions on the "ViewCustomers" view we just created.

MacBook-Pro-121(mongod-3.4.0) FooBarFinancial> use admin
switched to db admin

MacBook-Pro-121(mongod-3.4.0) admin> db.createRole(
 { role: "CustomerServiceQuery",
 privileges: [ 
    { resource: 
       { db: "FooBarFinancial", collection: "ViewCustomers"},
         actions: ["find"] } ],
     } )

Next, we will create a new user for our web application to use called, "webuser" using the createUser function:

MacBook-Pro-121(mongod-3.4.0) admin> db.createUser( 
{ user: "webuser",
 pwd: "pass@word1",
 roles: [ { role: "CustomerServiceQuery", db: "admin" } ] } )

Now we are ready to test our new user's access to the data!

Querying the view with our new minimal privilege user

On a new window connect to MongoDB via the Mongo shell as follows:

Command Prompt> mongo --authenticationDatabase=admin -u webuser 
-p pass@word1

MongoDB shell version v3.4.0
connecting to: mongodb:
MongoDB server version: 3.4.0
MongoDB Enterprise > 

Note that we are connecting to MongoDB and specifying the admin database as our authentication database. This is because the admin database is where we created webuser. We could have also created the user in the FooBarFinancial database and used that as a authenticationDatabase. It is a best practice to leverage the admin database for user accounts. Now that we have authenticated notice that you as the webuser can't do much of anything. This user has no permissions other than executing the view which we gave them permission to do. For example, try viewing the databases via the "show dbs" command:

MongoDB Enterprise > show dbs
2017-01-04T12:16:59.399-0500 E QUERY    [main] Error: listDatabases failed:{
  "ok": 0,
  "errmsg": "not authorized on admin to execute command { listDatabases: 1.0 }",
  "code": 13,
  "codeName": "Unauthorized"
} :

Now, drum roll please... our web application needs to get access to our customers so they simply query the view as follows:

MongoDB Enterprise > use FooBarFinancial
switched to db FooBarFinancial
MongoDB Enterprise > db.ViewCustomers.find()
  "_id": ObjectId("586d2b17305dabd49d2c9417"),
  "first_name": "Rob",
  "last_name": "Walters",
  "city": "Boston",
  "state": "MA"

And there you have it all the sensitive info stripped and just the information the customer service web application needs. If an attacker compromised the webuser account or the web page they might be able to connect to MongoDB but all they would have access to is the information stored in this view.

Side Note: You may notice on the MongoDB shell an error following the execution of this query. Something with the text, "not authorized on FooBarFinancial to execute command { profile: -1.0 }". When we execute a query using the MongoDB shell it returns a cursor and some information like how many milliseconds the query took. This profile information requires yet another permission in order to be obtained and thus presents the error that you see. It is specific in this case to using the MongoDB shell in our example.

Some considerations when using read-only views

  • When a view is queried MongoDB will materialize the view with the latest values from the underlying collection. For example, consider the scenario where a customer address view is queried at time T0. At time T1, the customer address is updated. At time T2 the view is queried again and the results now reflect the latest value of the customer address.
  • Views can reference other views. They do not always have to reference a collection.
  • Indexes can't be created on views. However, they can be created on the underlying collections that the views are referencing.


The world is insecure and today more than ever we as application developers and administrators need to think of the security implications of everything we deploy. The developers at MongoDB think no different and with the recent release of 3.4 provide another security related feature called Read-only Views(ROV). ROVs provide a way for administrators to separate access to the underlying data from the user requesting the data. This feature supports the principle of least privileged software architecture.

You can learn more about MongoDB read-only views from the documentation.

Download the MongoDB Security Reference Architecture Guide

About the author: Robert Walters is a Senior Solutions Architect at MongoDB based in the Boston, Massachusetts area. Robert has spent almost 20 years working with database technologies and authored many technical books and whitepapers. In addition he has co-authored three patents while working on the SQL Server product team at Microsoft.