Book Image

Learn MongoDB 4.x

By : Doug Bierer
Book Image

Learn MongoDB 4.x

By: Doug Bierer

Overview of this book

When it comes to managing a high volume of unstructured and non-relational datasets, MongoDB is the defacto database management system (DBMS) for DBAs and data architects. This updated book includes the latest release and covers every feature in MongoDB 4.x, while helping you get hands-on with building a MongoDB database app. You’ll get to grips with MongoDB 4.x concepts such as indexes, database design, data modeling, authentication, and aggregation. As you progress, you’ll cover tasks such as performing routine operations when developing a dynamic database-driven website. Using examples, you’ll learn how to work with queries and regular database operations. The book will not only guide you through design and implementation, but also help you monitor operations to achieve optimal performance and secure your MongoDB database systems. You’ll also be introduced to advanced techniques such as aggregation, map-reduce, complex queries, and generating ad hoc financial reports on the fly. Later, the book shows you how to work with multiple collections as well as embedded arrays and documents, before finally exploring key topics such as replication, sharding, and security using practical examples. By the end of this book, you’ll be well-versed with MongoDB 4.x and be able to perform development and administrative tasks associated with this NoSQL database.
Table of Contents (22 chapters)
1
Section 1: Essentials
5
Section 2: Building a Database-Driven Web Application
9
Section 3: Digging Deeper
13
Section 4: Replication, Sharding, and Security in a Financial Environment
14
Working with Complex Documents Across Collections

Enforcing uniqueness

Once you have settled on an algorithm for choosing a unique key, is there a way to guarantee uniqueness? One very useful and effective solution is to create a unique index on the key field. This has two benefits:

  • MongoDB prevents your application from adding a document with a duplicate key.
  • Searches involving this key becomes faster and more efficient.
The general rule for creating indexes in MongoDB is to create indexes on fields frequently used in queries. Do not go overboard on creating indexes, however, as they introduce extra overhead to maintain them. 

Using the mongo shell, you can create an index on a field as follows:

db.<name_of_collection>.createIndex(keys, options);

Let's jump right into an example involving the users collection and the userKey field mentioned earlier in this subsection. Here is the query that creates a unique index on the userKey field in ascending order:

db.users.createIndex( { "userKey" : 1 }, { "unique...