Define and use variables in MongoDB Shell (mongosh)

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

In this tutorial, we will explore how to define and use variables within the MongoDB Shell, or mongosh. If you’re new to MongoDB or need an introduction on how to use its shell, then you’re in the right place. Variables in mongosh can greatly enhance the readability and reusability of your commands. We will start with the basics and progress to more advanced examples, so whether you’re just starting out or looking to polish your skills, this guide will prove helpful.

Setting up MongoDB Shell

Before we get started, make sure that MongoDB is installed in your system and that the MongoDB server (mongod) is running. You can launch the shell (mongosh) simply by typing mongosh in your command line. Once you’ve accessed the shell, you can start issuing commands to interact with your databases and collections.

Defining Basic Variables

const dbName = 'myDatabase';
use dbName;

In this example, we define a constant variable dbName with the value 'myDatabase'. We then use this variable to switch to the database by using the use command.

Inserting Documents with Variables

const userCollection = 'users';
db[userCollection].insertOne({ name: 'John Doe', age: 30 });

Here, we use a variable to represent our collection name. We can then pass this variable to our database operations to interact with the collection. This example show inserting a single document into our ‘users’ collection.

Querying with Variables

const query = { age: { $gte: 18 } };
const adults = db[userCollection].find(query);

adults.forEach(adult => {
 printjson(adult);
});

Variables can also hold query objects. Here, we use the find method with a query that filters users who are 18 or older. We then iterate over the resulting cursor and print each document.

Updating Documents Using Variables

const updateFilter = { name: 'John Doe' };
const updateQuery = { $inc: { age: 1 } };
db[userCollection].updateOne(updateFilter, updateQuery);

To update one or more documents, we define variables for our filter and our update query. In this case, we increment the age of ‘John Doe’ by 1.

Working with Aggregation

Simple Aggregation

const pipeline = [
  { $match: { age: { $gte: 18 } } },
  { $count: 'adultCount' }
];
const result = db[userCollection].aggregate(pipeline).toArray();
printjson(result);

Aggregations can also benefit from the use of variables. Here, we define a pipeline that matches documents and then counts the total number of adults. We then print the result.

Complex Aggregation

const complexPipeline = [
  {
    $lookup: {
      from: 'transactions',
      localField: '_id',
      foreignField: 'userId',
      as: 'transactions'
    }
  },
  {
    $addFields: {
      totalSpent: {
        $sum: '$transactions.amount'
      }
    }
  }
];
const spendingData = db[userCollection].aggregate(complexPipeline).toArray();
spendingData.forEach(doc => {
  printjson(doc);
});

In a more complex example, we use variables to define an aggregation pipeline that includes a $lookup for joining documents from another collection, then adds a field calculating total spending per user. We output each enriched user document.

Using Variables with JavaScript Functions

Reusable Query Functions

function findUsersByAge(minAge) {
  const query = { age: { $gte: minAge } };
  const users = db[userCollection].find(query).toArray();
  return users;
}

findUsersByAge(18).forEach(user => {
  printjson(user);
});

We can take our usage of variables further in the shell by defining custom JavaScript functions. This function lets us query users by a minimum age by simply passing it as an argument.

Transactional Scripts

const session = db.getMongo().startSession();
session.startTransaction();
try {
  // your transaction code hereusing variables and operations
  session.commitTransaction();
} catch (e) {
  print('Transaction failed: ', e);
  session.abortTransaction();
}

Here we use variables to define a transaction session, start the transaction, and make our changes within a try-catch block. In the case of an error, we catch it, print an error message and abort the transaction.

Conclusion

As we’ve seen throughout this tutorial, variables in MongoDB Shell are not only useful for simplifying commands but are also invaluable for crafting readable code patterns and reusing logic. This not only speeds up the development process but also minimizes the potential for manual errors. From defining simple constants to complex aggregation pipelines and transactional scripting, the flexibility of using variables with the power of JavaScript functions in mongosh stands clear.