Exploring MongoDB Aggregation Stages: Code Examples and Applications - Part 2

If you missed Part 1, get a quick look here.

$indexStats:

This example returns statistics on the usage of each index in the collection, including the name of the index, the number of accesses, and the size of the index.

db.collection.aggregate([
   { $indexStats: { } }
])

$redAct:

This example hides or masks data in the documents based on specified conditions. The "DESCEND"expressionallowstheaggregationtocontinueprocessingthedocumentsandthe"PRUNE" expression stops processing and hides the data in the documents. In this example, the documents with a "level" field equal to 1 will be processed, while the documents with a "level" field other than 1 will be hidden.

db.collection.aggregate([
   { $redact: {
      $cond: [
         { $eq: [ "$level", 1 ] },
         "$$DESCEND",
         "$$PRUNE"
      ]
   } }
])

$replaceRoot:

This example replaces the root document with a specified expression. In this example, the new root document is created by merging the existing root document with the contents of the "newField" field.

db.collection.aggregate([
   { $replaceRoot: { newRoot: { $mergeObjects: [ "$root", "$newField" ] } } }
])

$sample:

This example returns a random sample of documents from the collection. The "size" option specifies the number of documents to include in the sample.

db.collection.aggregate([
   { $sample: { size: 5 } }
])

$set:

This example changes the value of the "field1" field in the documents to "newValue".

db.collection.aggregate([
   { $set: { "field1": "newValue" } }
])

$zip:

This example applies a specified expression to each corresponding element of multiple arrays in the documents. In this example, the expression is the "$zip" stage and the "inputs" option specifies the arrays to be combined. The "useLongestLength" option specifies that the arrays should be padded with null values to match the length of the longest array.

db.collection.aggregate([
   { $zip: { inputs: [ "$field1", "$field2" ], useLongestLength: true } }
])

Still More coming:

These are just a few more examples of how to use aggregation stages in MongoDB. By using these stages in combination with other stages and expressions, you can perform complex data analysis and manipulation tasks on your collections.

Stay Tuned.....