MongoDB - Projecting derived fields using $project

Let us understand how we can project derived fields in MongoDB. We will not be able use find and project the derived fields. To project derived fields we need to use $project which is part of aggregation framework.

Here are few examples to use project.

Get order_item_subtotal from order_item_details along with order_id

db.orderDetails.aggregate([
  {
    $unwind: "$order_item_details"
  },
  {
    $project: 
      { 
        "order_id": 1,
        "order_item_subtotal":  "$order_item_details.order_item_subtotal",
        "_id": 0
      }
  }
]).pretty()