Working with MongoDB Views

Section
Materials

If you’ve worked with SQL relational databases, you’re no doubt familiar with views.

A view is a named query that’s saved to the database and runs whenever you call it.

Views in MongoDB are similar to SQL views, except that MongoDB views are limited to aggregation queries.

A view provides a way to save an aggregation and run it on demand, without persisting data to disk.

When you call a view, MongoDB executes the query and returns the data from the underlying collection, as though you queried the collection directly.

In this section, you’ll create a view based on data in the customers collection that you set up at the beginning of this course.

The view will be based on a predefined aggregation query that groups data by the package and prio_support fields and then provides the total number of transactions per group.

After you create the view, you’ll use various methods available to Studio 3T to retrieve data through that view.

Next, you’ll update the view definition, and then you’ll delete the view to return the database to its original state.

The MongoDB createview method

A MongoDB view abstracts a collection’s underlying document structure, returning only the data defined by the view’s aggregation.

This abstraction offers several important benefits, such as simplifying code maintenance, streamlining application development, and protecting personal information.

Views are easy to create and take up little disk space because only the view definition itself is persisted to the database. However, they can be used only to read data, not update or delete it. 

To create a view, you can use the MongoDB createView method.

MongoDB saves the view as a named database object. The view must be created in the same database that contains the collection targeted by the view. After the view has been created, you can query it as you would query a collection. 

The following syntax shows the basic elements that make up a view definition:

db.createView(<name>, <collection>, <pipeline>[, collation: <options> ])

The MongoDB createView method takes four arguments, as indicated by the placeholders. You should substitute the placeholders as follows:

  • Replace the <name> placeholder with the name you want to assign to the view.
  • Replace the <collection> placeholder with the name of the target collection.
  • Replace the <pipeline> placeholder with an aggregation pipeline, which is an array made up of one or more stages.
    The pipeline is similar to what’s used for the aggregate method, except with a few minor differences. For example, the createView pipeline does not support the $out or $merge operator. 
  • The collation argument is optional. If you include it, replace the <options> placeholder with a document containing the language-specific rules you want applied to string comparisons.

The best way to understand the createView method is to see an example.

The following statement defines a view named get_totals, which aggregates data in the customers collection in the sales database:

db.createView(
   "get_totals",
   "customers",
  [
    {
      "$match" : { 
        "transactions" : { 
          "$gt" : NumberLong(0) } }
    }, 
    {
      "$group" : { 
        "_id" : { 
          "package" : "$package" }, 
          "SUM(transactions)" : { "$sum" : "$transactions" } } 
    }, 
    { 
      "$project" : { 
        "package" : "$_id.package", 
        "total" : "$SUM(transactions)", 
        "_id" : NumberInt(0) }
    }
  ]
);

The MongoDB createView method’s first argument specifies the view’s name (get_totals), and the second argument identifies that target collection (customers). The third argument is an array that defines three pipeline stages:

  • The $match stage limits the documents to those that have a transactions value greater than 0.
  • The $group stage groups the documents based on the package values and then provides the total number of transactions for each package type.
  • The $project stage specifies that the query should return the package and total fields, but not the _id field.

When you run this statement, MongoDB saves the get_totals view object to the sales database, where it can be accessed at any time, much like a collection.

For example, a user can run a find statement or aggregate statement against the view, further refining the returned data. The query engine does not run the view’s aggregate query until that view is actually called.

Understanding the createView statement is useful in learning about how views work, but know that Studio 3T provides tools that make it easy to create, update, and delete views, without having to build or modify your own createView statements.

For example, you can use the View Editor to create and edit views as easily as you can create aggregations.

After you create the view, you can then query it using the various methods available in Studio 3T for accessing document data, as you’ll see in the following exercises.

By the end of this section, you will learn how to:

  • Create a MongoDB view
  • Query a MongoDB view
  • Modify and delete a MongoDB view

What you will need:

  • Access to a MongoDB Atlas cluster
  • Access to the customers collection in the sales database
Log in

Log in to your Studio 3T Academy account

Forgot password?

Don't have an account yet? Sign up
Sign up

Start learning MongoDB today. All fields are mandatory.

By signing up for a course, you agree to the 3T Software Labs Privacy Policy.


Already have an account? Log in