mongo-db
  1. mongo-db-rename-operator

MongoDB $rename Operator

The $rename operator in MongoDB is used to rename fields within a document. It is commonly employed within the $project stage of an aggregation pipeline to rename one or more fields. This guide will cover the syntax, examples, output, explanations, use cases, important points, and a summary of using the $rename operator in MongoDB aggregation.

Syntax

{ $project: { newFieldName: "$oldFieldName", ... } }
  • $project: Aggregation stage to reshape documents.
  • newFieldName: The new name for the field.
  • $oldFieldName: The existing field name to be renamed.

Example

Consider a collection named employees with documents containing empName and empDept fields. We want to rename these fields to name and department, respectively.

db.employees.aggregate([
  {
    $project: {
      name: "$empName",
      department: "$empDept"
    }
  }
]);

Output

The output will display documents with the renamed fields name and department.

[
  { "_id": ObjectId("..."), "name": "Alice", "department": "IT" },
  { "_id": ObjectId("..."), "name": "Bob", "department": "HR" },
  // ... other documents
]

Explanation

  • The $project stage is used to reshape documents, providing new names (name and department) for the existing fields (empName and empDept).

Use

The $rename operator in MongoDB is used for:

  • Renaming fields within documents to improve readability or match a specific naming convention.
  • Creating new fields with more meaningful names based on existing field values.

Important Points

  • The $rename operation is part of the $project stage.
  • It allows for renaming multiple fields within a single aggregation stage.
  • The original field names can be referenced using the $ (dollar) sign.

Summary

The $rename operator in MongoDB provides a flexible way to rename fields within documents during the aggregation pipeline. It is useful for creating more descriptive field names or adhering to a standardized naming convention. Understanding how to use the $rename operator is valuable for MongoDB developers working with aggregation pipelines to reshape and enhance documents.

Published on: