MongoDB: Set default value for a field (with examples)

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

Introduction to Default Values

When working with databases, a default value is the value that a database field will assume if no value has been provided for it during a document insertion. This feature is extremely useful in managing data integrity and setting predictable base-line values for application logic.

In this tutorial, we’re going to dive deep into how to set default values for a field in MongoDB. Understanding how to set default values is crucial for ensuring data consistency and quality in your database operations. This knowledge not only enhances your database schema design but also ensures that your applications behave predictably when interacting with your MongoDB databases.

Basic Setting of Default Values

Let’s start with the basics. In MongoDB, unlike some traditional SQL databases, setting default values is generally handled at the application level, rather than being directly embedded into the database schema definition during creation. However, with MongoDB’s flexible schema and the Mongoose ODM (Object Document Mapping) for Node.js, default value setup becomes streamlined.

Example 1: Using Mongoose to set default values

// Define a Schema
const userSchema = new mongoose.Schema({
  name: String,
  registered: {
    type: Date,
    default: Date.now
  }
});

// Compile model from schema
const User = mongoose.model('User', userSchema);

This simple schema for a user model demonstrates how to set a default value for the ‘registered’ field. Whenever a new document is created without specifying the ‘registered’ date, MongoDB automatically uses the current date and time.

Advanced Techniques

Moving beyond the basic application-level defaults, MongoDB provides several techniques to achieve more complex default value settings, including the use of database triggers and MongoDB functions.

Example 2: MongoDB Atlas Triggers for Default Values

MongoDB Atlas, MongoDB’s fully-managed cloud service, offers the ability to use triggers to automatically set or alter a field’s value when certain conditions are met. This method can be particularly useful for complex default setting scenarios that cannot be easily handled at the application layer.

Creating a trigger in MongoDB Atlas involves writing a function that is executed in response to database events. For instance, you can create a trigger that sets a default ‘points’ field value for a new document in a ‘users’ collection.

// Example trigger function using MongoDB Atlas that sets default values
exports = function(changeEvent) {
  const collection = context.services.get('mongodb-atlas').db('your-db-name').collection('your-collection-name');
  if (changeEvent.operationType === 'insert') {
    const defaultPoints = 100;
    collection.updateOne(
      { _id: changeEvent.documentKey._id },
      { $set: { points: defaultPoints } }
    );
  }
};

Using MongoDB Defaults in Aggregate Operations

Another advanced technique involves using MongoDB’s aggregation framework to dynamically assign default values during query operations. This approach is especially useful when you want to integrate default values into the results of complex queries and manipulations without permanently altering the document in the collection.

Example 3: Dynamically assigning defaults with aggregation

// Using the $ifNull operator to assign a default value in an aggregation pipeline
const pipeline = [
  {
    $project: {
      name: 1,
      level: { $ifNull: ["$level", "Novice"] }
    }
  }
];

This example showcases how to use MongoDB’s aggregation framework to assign a ‘Novice’ default value to the ‘level’ field if it doesn’t already have a value, all within the confines of a data aggregation operation. This technique is particularly handy for reporting and data analysis scenarios where data completeness is crucial.

Conclusion

Setting default values in MongoDB, whether through application logic with Mongoose, using MongoDB Atlas triggers, or dynamically through aggregation operations, ensures that your databases maintain a consistent state and that your applications interact with your data predictively. With the concepts and examples presented in this tutorial, you’re well-equipped to implement default value settings in your MongoDB databases, enhancing data integrity and application consistency.