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 TTL-based indexes


In this recipe, we will explore the expireAfterSeconds property of MongoDB indexes to allow automatic deletion of documents from a collection.

Getting ready

For this recipe, all you need is a mongod instance running. We will be creating and working on a new collection called ttlcol in the database mydb.

How to do it...

  1. Ensure that our collection is empty:
db.ttlcol.drop()
  1. Add 200 random documents:
for(var x=1; x<=100; x++){
  var past = new Date()
  past.setSeconds(past.getSeconds() - (x * 60))
  // Insert a document with timestamp in the past
  var doc = {
    foo: 'bar',
    timestamp: past
  }
  db.ttlcol.insert(doc)
  // Insert a document with timestamp in the future
  var future = new Date()
  future.setSeconds(future.getSeconds() + (x * 60))
  var doc = {
    foo: 'bar',
    timestamp: future
  }
  db.ttlcol.insert(doc)
}
  1. Check that the documents were added:
db.ttlcol.count()
  1. Create an index with TTL:
db.ttlcol.createIndex({timestamp:1}, {expireAfterSeconds: 10}...