Efficient Aggregate Pipeline Testing in MongoDB

MongoDB provides a nifty way to test your aggregation pipeline before writing a single line of code from their UI. I use MongoDB Compass for this but you can also try this from the MongoDB Atlas UI.

Go to the collection you want to try it on > Click on Aggregation > Now add the stages you want to try

Let's take an example of getting Pinterest boards of users who have successfully onboarded using different stages:

  1. Stage 1: Get boards that are active (not deleted) using $match

  1. Stage 2: Use $lookup to look those users up from users collection and add them as author

  2. Stage 3: Use $unwind to deconstruct the author array

As you can see, with each stage we can see the resulting output. This helps a lot to tweak your query according to your need.

  1. Finally, use the $match query to add a check for onboardingDone field

After you are done with your query, you can easily export the pipeline you created using the export option

Here's what the final pipeline looks like:

[
  {
    '$match': {
      'isActive': true
    }
  }, {
    '$lookup': {
      'from': 'users', 
      'localField': 'user', 
      'foreignField': '_id', 
      'as': 'author'
    }
  }, {
    '$unwind': {
      'path': '$author'
    }
  }, {
    '$match': {
      'author.onboardingDone': true
    }
  }
]

As always, feel free to add suggestions or feedback :)

#mongodb