Adding Indexes

MongoDB allows you to index fields in your collections so that you can more quickly find documents. When you add an index in MongoDB, a special data structure is created in the background that stores a small portion of a collection’s data and then optimizes the structure of that data to make it faster to find specific documents.

For example, applying an _id index basically creates a sorted array of _id values. Once the index has been created, you get these benefits:

Image When looking up an object by _id, you can perform an optimized search on the ordered index to find the object in question.

Image Say that you want objects back sorted by _id. The sort has already been performed on the index, so it doesn’t need to be done again. MongoDB just needs to read the documents in the order in which their _id appears in the index.

Image If you want documents 10–20 sorted by _id, the operation is just a matter of slicing that chunk out of the index to get the _id values so you can look up objects.

Image Best of all, if all you need is a list of sorted _id values, MongoDB does not even need to read the documents at all; it can just return the values directly from the index.

You need to keep in mind, however, that those benefits come at a cost. The following are some of the costs associated with indexes:

Image Indexes take up space on disk and in memory.

Image Indexes take up processing time when you’re inserting and updating documents. Therefore, database writes to collections with large number of indexes can suffer performance hits.

Image The larger the collection, the greater the cost in terms of resources and performance. With extremely large collections, it may be impractical to apply some indexes.

Several different types of indexes can be applied to fields in a collection to support various design requirements. Table 17.1 lists the different index types.

Image
Image

Table 17.1 Types of indexes supported by MongoDB

You can give indexes special properties to define how MongoDB will handle the index:

Image unique: This property forces the index to include only a single instance of each field value, and thus MongoDB will reject adding a document that has a duplicate value to one that is already in the index.

Image sparse: This property ensures that the index will contain only entries for documents that have the indexed field. The index will skip documents that do not have the indexed field.

Image TTL: TTL, or time-to-live, indexes apply the concept of allowing documents to exist in the index only for a certain amount of time (for example, log entries or event data that should be cleaned up after a certain amount of time). The index keeps track of insertion time and removes the earliest items after they have expired.

You can combine the unique and sparse properties so that an index will reject documents that have a duplicate value for the index field and reject document that do not include the indexed field.

You can create indexes from the MongoDB shell, MongoDB Node.js native client, or Mongoose. To create an index from the MongoDB shell, you use the ensureIndex(index, properties) method. For example:

db.myCollection.ensureIndex({name:1}, {background:true, unique:true, sparse: true})

The background option specifies whether the index created should take place in the foreground of the shell or the background. Running in the foreground completes faster but takes up more system resources—so it’s not a good idea on a production system during peak times.

To create an index from the MongoDB Node.js native driver, you can call the ensureIndex(collection, index, options, callback) method on an instance of the Db object. For example:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost/", function(err, db) {
  db.ensureIndex('myCollection', {name: 1},
                 {background: true, unique: true, sparse: true},
                 function(err){
    if(!err) console.log("Index Created");
  });
});

To create an index using the Schema object in Mongoose, you set the index options on the field in the schema. For example:

var s = new Schema({ name: { type: String, index: true, unique: true, sparse: true});

You can also add the index to the Schema object later by using the index() method. For example:

s.schema.path.('some.path').index({unique: true, sparse: true});

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.154.89