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

$addFields:

db.collection.aggregate([
   { $addFields: { newField: { $sum: ["$field1", "$field2"] } } }
])

This example adds a new field "newField" to the documents in the collection and sets its value to the sum of the values of "field1" and "field2".

$count:

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

This example counts the number of documents in the collection and returns the result as a single document with a field "count" containing the number of documents.

$facet:

db.collection.aggregate([
   { $facet: {
      firstStage: [
         { $match: { status: "A" } },
         { $group: { _id: "$permission", total: { $sum: "$score" } } }
      ],
      secondStage: [
         { $match: { status: "B" } },
         { $group: { _id: "$permission", total: { $sum: "$score" } } }
      ]
   } }
])

This example applies two different stages to the documents in the collection and returns the results as an array of sub-aggregation results. The first stage filters the documents to only include those with status "A" and groups them based on the "permission" field. The second stage filters the documents to only include those with status "B" and groups them based on the "permission" field.

$geoNear:

db.collection.aggregate([
   { $geoNear: {
      near: { type: "Point", coordinates: [longitude, latitude] },
      distanceField: "dist.calculated",
      maxDistance: 1000,
      spherical: true
   } }
])

This example returns the documents in the collection that are nearest to a specified location using the "longitude" and "latitude" values. The "distanceField" option specifies the name of the field that will contain the calculated distance. The "maxDistance" option sets a limit on the maximum distance to include in the result set. The "spherical" option specifies that spherical geometry should be used when calculating distances.

Not Done Yet... Will be on next part

These are just a few examples of how to use some of the additional aggregation stages in MongoDB. By combining these stages with other stages and expressions, you can perform a wide range of complex data analysis and manipulation tasks on your collections.