MongoDB aggregation: match a field with values in a list

TL, DR

MongoDB is one of the leading NoSQL databases, and its aggregation framework enables powerful queries, as well as data operations. We will see how to match a field with values in a list to help you select.

Matching values in a list

I already provided an introduction to MongoDB and Compass in a previous post for my MongoDB series. So you should know that Compass is the way to go for creating Aggregation pipelines.

In case you are overwhelmed by JavaScript as I do, you will find a bit complicated to get your head around the syntax you need to use to get the Aggregation pipeline delivering the results you want.

For this specific case, my goal is to select all records in the MongoDB collection where a certain field has a value which is included in a list. For instance, I want to get all records where the “category” field value is one of “Grocery”, “Fruit and Vegetables”, etc.

In Python you would have your trusty in operator (or .isin() methods in Pandas). Unfortunately, MongoDB has been built for JavaScript, and none of those keywords hold power there.

However, we got our trusty Google search and the great support of Compass to help us. All you need to do is to open you Aggregation tab in Compass, select a “$match” operator block, and write the following:

/**
 * query: The query in MQL.
 */
{
  category: {
    $in: [
      "Grocery",
      "Fruit and Vegetables",
      "Frozen products",
      // all the items you want!       
    ]
  }
}

The Aggregation tab will give you a preview of the results you will get, very helpful for debugging while you create your pipeline.

mongodb aggregation match value in list
Compass Aggregation tab. Sweet!

The piece of magic is the small icon near the the green “SAVE” button. Once you are done with the creation of your data pipeline, adding different stages and directly visualizing some results, you want to integrate this with the rest of your code. And yes, Python 3 is the option I select all the time!

mongodb aggregation match value in list
Compass exporting your data pipeline to Python3 code. Sweeter 🙂

You can grab the code, optionally include also the Driver Syntax (that will also include your MongoDB connection string, with username and password). And you are good to go! You can paste that code in your Jupyter notebook or Python file, and move on with your project.

I hope you find this useful! I plan to write more MongoDB-related posts over time, you can check them here!

  • MongoDB “$match” link
  • MongoDB related posts link

Do you like our content? Check more of our posts in our blog!