In this course, you will get introduced to MongoDB. You will learn how to install it and how to operate it via its shell. Moreover, you will learn how to programmatically access it via Java and how to leverage Map Reduce with it. Finally, more advanced concepts like sharding and replication will be explained. Check it out here!
In this final part of the tutorial we are going to take a look on MongoDB security model, different types of indexes, query plans and profiling, server-side cursors and bulk operations.
2. Security
MongoDB security features include authentication, authorization and auditing. Its foundation is a role-based access control with flexible set of privileges. It is worth mentioning that MongoDB provides a basis for user-defined roles by defining a set of build-in roles (for more details please refer to official documentation). As always, MongoDB shell provides rich set of command helpers to deal with security configuration.
The command updates user’s data with name username on the current database. Please notice that an update to a property completely replaces the previous property values (including updates to the user’s roles).
Example
In MongoDB shell, let us issue the command (to update the user created previously by createUser command):
The command updates the password for the existing user with name username.
Example
In MongoDB shell, let us issue the command (to drop the user created previously by createUser command): db.changeUserPassword("testuser", "newpassword")
The command returns information about one or more users on the database.
Example
In MongoDB shell, let us issue the command (to get the information about the user created previously by createUser command): db.getUser("testuser") (or alternatively, db.getUsers())
The command updates user-defined role with name rolename on the current database. Please notice that an update to a property completely replaces the previous property values (including updates to the roles and privileges).
Example
In MongoDB shell, let us issue the command (to update the role created previously by createRole command):
The command allows a user to authenticate to the database from within the MongoDB shell or client session.
Example
In MongoDB shell, let us issue the command (to authenticate session using the user created previously by createUser command): db.auth( "testuser", "testpassword" )
Choosing the right indexes may boost your query performance (and consequently applications performance) in most times. MongoDB supports different types of indexes to pick from:
_id: all collections have an index on the _id field that exists by default
single field: indexes on a single field of a document, f.e. { “title”: 1 }
multikey index: indexes on content stored in arrays, f.e. { “categories”: 1 }
geospatial index: 2d/2sphere indexes to support efficient geospatial queries, f.e. { “location”: “2d” }
text indexes: indexes on string content to support full-text search, f.e. { “title”: “text” }
hashed indexes: indexes to support hash-based sharding (please refer to Part 4. MongoDB Sharding Guide of the tutorial for more details)
Additionally, each index may be defined as:
unique: duplicate values for the indexed field will be rejected
sparse: index only contain entries for documents that have the indexed field
For indexed collections, the values for the indexed fields have a maximum index key length limit: the total size of an index entry must be less than 1024 bytes (please refer to limits and thresholds section of the official documentation).
MongoDB provides a very useful tool to collect server performance data: the database profiler. It collects fine grained data about queries, write operations, cursors, and other database commands on a running server instance. The profiling can be enabled on a per-database or per-server instance level.
Command
Profile
Parameters
{
profile: <level>
}
Wrapper
db.setProfilingLevel(level, slowms)
Description
The command modifies the current profiler level used by the database profiling system to capture data about performance. The level parameter has the following meaning:
-1 – No change. Returns the current profile level.
0 – Off. No profiling.
1 – On. Only includes slow operations.
2 – On. Includes all operations.
Example
In MongoDB shell, let us issue the command: db.setProfilingLevel(2)
To get more insights about analyzing the performance of database operations please refer to official documentation.
5. Query Cache
Among many other new features, MongoDB2.6 supports a new set of commands to view and manipulate the query cache:
list all known query shapes
display cached plans for a query shape
remove a query shape from the cache
clear the whole cache
The query optimizer executes queries and picks the most efficient query plan for a query given the defined indexes. Later on, this query plan is used each time the query (with such a shape) runs. The query optimizer only caches the plans for those query shapes that can have more than one viable plan and occasionally reevaluates query plans as the content of the collection changes.
To experiment with query plans, we need a small dataset and the example from Part 3. MongoDB and Java Tutorial is going to be handy again. Let us switch to books collection in bookstore database, create couple of indexes and insert a few documents into it using MongoDB shell.
Once the preparation is done, let us run simple query which will trigger the query plans evaluation: db.books.find( { "publisher.name": "O'Reilly" }, { "title": 1 } )
Command
db.<collection>.getPlanCache().help()
Description
The command displays the methods available for a collection’s query plan cache with brief description.
Example
In MongoDB shell, let us issue the command: db.books.getPlanCache().help()
The command clears the cached query plans for the specified query shape for collection collection. If the query shape is omitted, all cached query plans will be cleared.
Example
In MongoDB shell, let us issue the command: db.books.getPlanCache().clear()
With log level set to 1 or greater MongoDB will log plan cache changes. The log level could be set using the following command (please notice that it should be run in context of admin database): db.adminCommand( { setParameter: 1, logLevel: 1 } )
6. Cursors
Cursors are the basic way to access documents returned by read operations, f.e. db.<collection>.find(). In MongoDB shell, if the returned cursor is not assigned to a variable, then only first 20 documents are taken from the cursor and shown as the result. However, cursors are very powerful and provide a lot of useful methods.
Method
cursor.addOption(flag)
Description
The method adds special wire protocol flags that modify the behavior of the query.
The method returns a cursor that begins returning results only after passing or skipping a number of documents. It should be called before retrieving any documents from the database.
The method ensures that the query will not return a document multiple times, even if intervening write operations result in a move of the document due to the growth in document size. It should be called before retrieving any documents from the database and works with unsharded collections only.
The command allows applications to use multiple parallel cursors when reading all the documents from a collection. It returns a document that contains an array of cursor information.
Example
In MongoDB shell, let us issue the command: db.runCommand( { parallelCollectionScan: “books”, numCursors: 1 } )
Armored with deeper knowledge about cursors, let us take a look on the example of different cursor methods in action using the books collection from section Query Cache.
One of the coolest features of latest MongoDB2.6 release is the introduction of bulk API. In a nutshell, this new API supports ordered and unordered bulk operations. In an ordered bulkoperation, the execution of every operation follows the order it was added to the bulk operation. Consequently, in an unordered bulkoperation the order of every operation is not guaranteed.
Command
db.<collection>.initializeOrderedBulkOp()
Description
The command Initializes and returns a new ordered bulkoperation builder for a collection collection. The builder constructs an ordered list of the operations to be executed in bulk.
Example
In MongoDB shell, let us issue the command: var bulk = db.testcollection.initializeOrderedBulkOp()
The command Initializes and returns a new unordered bulkoperation builder for a collection collection. The builder constructs an unordered list of the operations to be executed in bulk.
Those two commands are the starting point to begin using the bulk API. They return bulk builder object (of type Bulk) which provides the fluent API to construct bulk operation.
Method
Bulk.insert(<document>)
Description
The method adds an insert operation to a bulk operations list.
To finish with the bulk API, let us create and execute an example bulk operation using MongoDB shell and initialization commands. In the example we are going to bulk the following actions:
insert 3 books into books collection
update all books by setting the categories field
update book’s (with title “MongoDB: The Definitive Guide”) categories with additional category
As you can see, each action within ordered bulk operation may rely on previous actions to succeed (for example, find/update depends on insert). This is not the case for unordered bulk operation. The execution of this bulk operation in MongoDB shell yields the following result document:
This section concludes the MongoDB tutorial. Hopefully, you have found this NoSQL document database fitting your current or future application demands and this tutorial has helped you to make the right decisions.
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
Andriy is a well-grounded software developer with more then 12 years of practical experience using Java/EE, C#/.NET, C++, Groovy, Ruby, functional programming (Scala), databases (MySQL, PostgreSQL, Oracle) and NoSQL solutions (MongoDB, Redis).