Book Image

MongoDB Administrator???s Guide

By : Cyrus Dasadia
Book Image

MongoDB Administrator???s Guide

By: Cyrus Dasadia

Overview of this book

MongoDB is a high-performance and feature-rich NoSQL database that forms the backbone of the systems that power many different organizations. Packed with many features that have become essential for many different types of software professional and incredibly easy to use, this cookbook contains more than 100 recipes to address the everyday challenges of working with MongoDB. Starting with database configuration, you will understand the indexing aspects of MongoDB. The book also includes practical recipes on how you can optimize your database query performance, perform diagnostics, and query debugging. You will also learn how to implement the core administration tasks required for high-availability and scalability, achieved through replica sets and sharding, respectively. You will also implement server security concepts such as authentication, user management, role-based access models, and TLS configuration. You will also learn how to back up and recover your database efficiently and monitor server performance. By the end of this book, you will have all the information you need—along with tips, tricks, and best practices—to implement a high-performance MongoDB solution.
Table of Contents (17 chapters)
Title Page
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Creating a unique index


MongoDB allows you to create an index on a field with the option of ensuring that it is unique in the collection. In this recipe, we will explore how it can be done.

Getting ready

For this recipe, we only need a running mongod instance.

How to do it...

  1. Connect to the mongo shell and insert a random document:
use mydb
db.testuniq.insert({foo: 'zoidberg'})
  1. Create an index with the unique parameter:
db.testuniq.createIndex({foo:1}, {unique:1})

The preceding command should give you an output similar to this:

{
  "createdCollectionAutomatically": false,
  "numIndexesAfter": 2,
  "numIndexesBefore": 1,
  "ok": 1
}
  1. Try to add another document with a duplicate value of the field:
db.testuniq.insert({foo: 'zoidberg'})

The preceding command should give you an error message similar to this:

WriteResult({
  "nInserted" : 0,
  "writeError" : {
    "code" : 11000,
    "errmsg" : "E11000 duplicate key error collection: mydb.testuniq index: foo_1 dup key: { : \"zoidberg\" }"
  }
})
  1. Drop the index...