Learn Indexing and The ensureIndex Method in MongoDB

Learn Indexing and The EnsureIndex Method In MongoDB    #javascript #coding #AngularJS

  • We are using the ‘ensureIndex ({“city”:1})’ method to create an index on the ‘city’ field of the documents in the ascending order.
  • In ‘ensureIndex ()’ method, we can pass multiple fields of a document in order to create an index on multiple fields.
  • The ensureIndex () Method In MongoDB, we use ‘ensureIndex ()’ method to create an index.
  • The ‘ensureIndex ()’ method accepts the following list of options which all are optional.
  • We are using the ‘save ()’ method to insert four records together as the bulk write operation in the MongoDB.

We will learn about Indexing and we are going to explore the ‘ensureIndex’ method to operate on the documents present inside a collection of MongoDB.

@jonatthan1992: Learn Indexing and The EnsureIndex Method In MongoDB #javascript #coding #AngularJS

In this chapter, we are going to explore the ‘ensureIndex’ method to operate on the documents present inside a collection of MongoDB.

We all are familiar with the index of a book which has all the chapters numbered. When we have to search for a specific chapter which is present in the middle of the book without using the index, then we will have to go page by page to find that chapter. However, on the book with index the page number is mentioned with which we can directly jump on to that chapter and hence it saves our time. In the similar way, Indexes in MongoDB save our time and make the processing of queries faster. Consider the situation without indexes in MongoDB, it will scan each and every document present in a collection to search those documents that matches the query criteria. This will be a very inefficient approach when MongoDB query has to search the required documents from a large volume of data.

Indexes in MongoDB are special data structures which are used to store a small portion of the data set in an easy-to-traverse form. They store the value of a specific field or more than one fields (i.e. set of fields), which are ordered by the value of the field as indicated in the index.

In MongoDB, we use ‘ensureIndex ()’ method to create an index. The following is the basic syntax for ‘ensureIndex ()’ method in the MongoDB.

The following is an example on using the ‘ensureIndex ()’ statement. Let’s insert 4 documents into a collection known as ‘index_demo_db’.

In this chapter, we have learnt about the practical use of the ‘ensureIndex ()’ method with the help of an example.

Learn Indexing and The ensureIndex Method in MongoDB