Haris Spahija
Haris Spahija

Reputation: 1

Match $and based on array of filter items in MongoDB

I have a Collection in MongoDB of CatalogItems. Every CatalogItem contains a product that has an array of metafields.

In these metafields there are 2 fields that are Brand_ID and Article_No

Example CatalogItem document:

CatalogItem = {
    product: {
      metafields: [
        {
          key: "Brand_ID",
          value: "317"
        },
        {
          key: "Article_No",
          value: "48630"
        }
      ]
    }
  }

I have an array of filters that is used to match the CatalogItems documents based on these metafields

filter array

filter = [
    { brandId: '317', articleId: '48630' },
    { brandId: '257', articleId: 'ZSA04036' }
  ]

I want to return all CatalogItems that match any of the exact combinations in filter. For example to return the stated CatalogItem I currently use this query

// Checks for { brandId: '317', articleId: '48630' }
query = {
    $and: [
      { "product.metafields": { $elemMatch: { key: "Brand_ID", value: filter[0].brandId } } },
      { "product.metafields": { $elemMatch: { key: "Article_No", value: filter[0].articleId } } },
    ]
  }

The issue that I have is that in order for me to look trough all the filter items I have to increment the filter index and rerunning the query.

For example looking for the second filter index I would have to change filter[0].brandId to filter[1].brandId

Is there a way in Mongo to query using a predefined array of objects instead of rerunning the query multiple times?

Upvotes: 0

Views: 81

Answers (1)

Haris Spahija
Haris Spahija

Reputation: 1

I figured out a way to set variables to the query using $or and .forEach()

let query = {
    $or: []
  };
 filter = [
    { brandId: '317', articleId: '48630' },
    { brandId: '257', articleId: 'ZSA04036' }
  ]

 filter.forEach(filterItem => {
    query.$or.push(
      {
        $and: [
          { "product.metafields": { $elemMatch: { key: "Brand_ID", value: filterItem.brandId } } },
          { "product.metafields": { $elemMatch: { key: "Article_No", value: filterItem.articleId } } },
        ]
      }
    )
  })

Upvotes: 0

Related Questions