The Journey of 100DaysofCode aka 100DaysofMongoDB (@Aasawari_24)

Day03 of MongoDB as 100DaysOfMongoDB

Extending the Aggregations learnings here:

The $project stage of aggregation is confusing yet very use pipeline step while we wish to query data in a specific manner. On one hand where $project allows us to figure which fields to include and exclude it however seems to be extremely confusing and inflexible at the same time.

Later in the 4.2 version of MongoDB, $set and $unset version was introduced which lead me into the ambiguity to use $set/$unset or $project operation.

The $set and $unset can be used when you require a minimal change in the output documents where as $project is recommended to be used when you need more changes in the output document than the input fields.

Consider the following dataset to understand the usage of $set and $unset

{
  _id: ObjectId("6044faa70b2c21f8705d8954"),
  employee_name: "Mrs. Jane A. Doe",
  employee_num: "1234567890123456",
  id_validity: "2023-08-31T23:59:59.736Z",
  joining_date: "2021-01-13T09:32:07.000Z",
  reportedTo: "Mr. X",  
  amex_card: "Credit",
  joined: True
}

Consider the change is required to convert the field id_validity from test to type Date.

[
  {"$set": {
    "joining_Date": {"$dateFromString": {"dateString": "$id_validity"}},
    "amex_card": "CREDIT",        
  }},
  
  {"$unset": [
    "_id",
  ]},
]

Now consider an example where you need information in the format:

{
  transaction_info: { 
    date: ISODate("2021-01-13T09:32:07.000Z")
  },
  joined: true
}

the best way to use aggregation here would be:

[   {"$project": {     
      date:  "$joining_date",
      "status": 
                 {"$cond": 
                       {"if": "$joined", "then": "JOINED", "else": "YET TO JOIN"}},    
        "_id": 0,
  }},
 ]
6 Likes