Projection, Sorting & Indexing in MongoDB

1. Introduction to projection

Projection is a way of selecting only the needed data rather than selecting whole of the data of a document. If a document has 10 fields and you need to show only 4, then select only 4 fields from them.

1.1 find() method

This method, explained in MongoDB Query operation accepts second optional parameter that is list of fields that you want to retrieve. When you execute find() method, it displays all fields of a document. To limit this, you need to set a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the fields.



1.1.1 Select only specific fields from the document the document in find query

The following are examples for selecting specific fields from a document:
Example 1:

db.inventory.find( { type: 'food' }, { item: 1, qty: 1, _id:0 } )

item:1 means item is included
qty:1 means qty is included
_id:0 means _id field is excluded

Example 2:

db.inventory.find( { type: 'food' }, { type: 0} )

all field except “type” will be displayed

1.1.2 Select specific fields in embedded documents

The following code snipet shows how to select specific fields in embedded documents:

        type: 'food', _id: 3 
        "classification.category": 1, _id: 0 

2. Introduction to Sorting

Here, we’ll learn how to sort records. We make use of sort() method to carry on sorting.


2.1 To Sort in Ascending Order of field value

The following code snipet shows how to sort document in Ascending Order of field value:


2.2 To Sort in Descending Order of field value

The following code snipet shows how to sort document in Descending Order of field value:

db.<COLLECTION>.find().sort({<field>: -1 })

3. Introduction to Indexing

Indexes support the efficient resolution of queries. Without indexes, MongoDB must look through every document of a collection to select those documents that match the query statement. This scan is highly inefficient and require MongoDB to process a large volume of data.

Indexes are special data structures, that store a small portion of the data set in an easy-to-traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in the index.



Example for indexing values in a document: