1 year ago

#354905

test-img

Ahnaf Ahmed

How to match documents of same collection in a lookup where an array field has the highest number of matching elements?

I have a products collection with a schema as follows:

    {
    brand: String,
    category: String,
    title: String,
    description: String,
    product_variants: [...],
    tags: [{label:String},{value:String}],
    }

I am performing a lookup in the same collection to add a field consisting of related products for each product. I need to get related products by matching documents that have similar elements in the tags array. So far I have the got the following lookup pipeline:

{
      $lookup: {
          from: 'products',
          let: { "tags": "$tags.label" },
          pipeline: [{
              $match: {'product_variants.status': {$eq: 'Active'}}
          },
          {
              '$match': {
                  '$expr': {
                      '$in': ['$tags.label', '$$tags']
                  }
              },
          },
          {
              $match: { 'product_variants': {
                  $elemMatch: {
                      'variant_details': {
                          $elemMatch: {
                              'inventory': {
                                  $elemMatch: {
                                      quantity: {$gt:0},
                                  }
                              }
                          }
                      }
                  }
              }}
          }, {
              $project: {
                  product_variants: {
                      "$filter": {
                          "input": {
                              "$map": {
                                  "input": "$product_variants",
                                  "as": "variants",
                                  "in": {
                                      "variant_code": "$$variants.variant_code",
                                      "images": {$slice: ["$$variants.images", 1]},
                                      "slug": "$$variants.slug"
                                  }
                              }
                          },
                          "as": "related_products",
                          "cond":{$gt: [{$size: "$$related_products.images"}, 0]}
                      }
                  }
              }
          }, { $limit: 3 } ],
          
          "as": "related_products"
      }
  },

I have tried using $all operator but it is not working either.

database

mongodb

mongoose

nosql

aggregation

0 Answers

Your Answer

Accepted video resources