Sling Academy
Home/MongoDB/MongoDB: How to modify/remove a view (with examples)

MongoDB: How to modify/remove a view (with examples)

Last updated: February 01, 2024

Introduction

MongoDB, a NoSQL database, has been a preferred choice for many developers owing to its flexibility, scalable structure, and powerful querying capabilities. Amongst its many features, MongoDB views are a boon for people looking to query the database without affecting the content or structure of collections. Views in MongoDB are read-only; they are not physically stored except as an aggregation pipeline against existing collections. But just like collections, views may sometimes need to be modified or removed entirely. This tutorial will walk you through how you can modify and remove views in MongoDB.

Working with MongoDB Views

MongoDB views are the result sets of an aggregation query. They are similar to views in SQL and are virtual; meaning, they do not store data themselves but display data processed by an aggregation pipeline run on collections. It provides a way to present data in different formats or to restrict the visibility of data for security purposes.

Creating a Basic View

Before we get into modification and deletion, let’s briefly go over how to create a view. This will serve as the foundation for our future operations:

db.createCollection('myCollection', { viewOn: 'sourceCollection', pipeline: [{ $match: { status: 'active' }}] });

The above command creates a view called ‘myCollection’ which shows documents from ‘sourceCollection’ where the ‘status’ field is ‘active’. The ‘pipeline’ defines what gets displayed in the view.

Modifying a View

Contrary to what many would expect, views in MongoDB cannot be directly updated like regular documents within a collection, due to their read-only nature. To modify a view, you essentially have to replace it using the db.createCollection() command with the same view name.

db.createCollection('myCollection', { viewOn: 'sourceCollection', pipeline: [{ $match: { status: 'active', userType: 'admin' }}] });

Here, we have modified ‘myCollection’ view to now filter by ‘status’ and ‘userType’. This replaces the existing view entirely, maintaining the same name but with a different aggregation pipeline.

Modifying a View with Additional Stages

If we want to get a little more advanced, we might add further stages to our aggregation pipeline. Let’s say you want to include a sort operation:

db.createCollection('myCollection', {
    viewOn: 'sourceCollection',
    pipeline: [
        { $match: { status: 'active', userType: 'admin' } },
        { $sort: { username: 1 } }
    ]
});

This would modify ‘myCollection’ to sort the resulting documents by the username in ascending order (1 indicates ascending order, while -1 would indicate descending order).

Removing a View

To remove a view in MongoDB, you follow the same process as when you drop a collection:

db.myCollection.drop();

This command will permanently delete the ‘myCollection’ view from the database. Be sure that you want to remove the view, as this action cannot be undone.

Advanced Examples

Chaining Aggregations

For more intricate processing, you can chain multiple aggregation stages:

db.createCollection('complexView', {
    viewOn: 'sourceCollection',
    pipeline: [
        { $match: { status: 'active' } },
        { $group: { _id: '$userType', count: { $sum: 1 }} },
        { $sort: { _id: 1 } }
    ]
});

This creates a view where documents are first filtered by ‘status’, then grouped by ‘userType’, and finally sorted by ‘userType’.

Indexing on Views

While you cannot directly create indexes on views, you can create indexes on the underlying collections used in the view or on the fields involved in the view’s aggregation pipeline to improve performance:

db.sourceCollection.createIndex({ userType: 1 });

Your view’s performance might see improvement, assuming your view makes promotions of those fields.

Troubleshooting

When working with views, there may be times you encounter issues or errors. For one, if you try to drop a view in a way other than using db.collection.drop(), you may get errors. Also note that not all client frameworks and library versions may seamlessly work with MongoDB views, so ensure compatibility when attempting to modify or remove views through anything other than the mongo shell or similar interface.

Conclusion

In this tutorial, you have learned how to effectively modify and remove views in MongoDB. You now understand that views are modified through the recreation of the view, and removal is as simple as dropping a collection. With great power comes great responsibility – ensure you modify and delete with caution, and always make these changes in your development environment first before your production database.

Next Article: MongoDB: How to temporarily disable a user

Previous Article: MongoDB: How to create and query a view

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)