deep search for nested document in mongodb with Laravel

52 Views Asked by At

I am pretty new in mongodb and i am using laravel framework. I am stuck in one stituation where i need to search with deep nested document. I have products collection that is below:-

db={
    "products": [
      {
        "_id": "655c3285822c4a52150c30a7",
        "name": "Bag Product",
        "variants": [
          {
            "variant_name": "Full Case",
            "attributes": [
              {
                "attribute_name": "Slots",
                "options": [
                  {
                    "name": "0.18"
                  },
                  {
                    "name": "0.22"
                  }
                ]
              },
              {
                "attribute_name": "Test Slot",
                "options": [
                  {
                    "name": "s1"
                  }
                ]
              }
            ]
          }
        ]
      },
      {
        "_id": "655c3285822c4a52150c30ab",
        "name": "Kit Product"
      }
    ]
  }

In this document we have multiple variants and each variants have multiple attributes.. Variant search is working fine but i want to search with attribute where attribte name is Slots. so if Slots is searched so other attributes should not come. My query so far in mongo db and laravel.

//mongo query
db.products.find({
      "name": "Bag Product"
    },
    {
      variants: {
        $elemMatch: {
          variant_name: "Full Case"
        }
      }
    })
 
//laravel query    
 $projectArray = [
        'variants' => [
            '$elemMatch' => ['variant_name' => "Full Case"]
        ],
    ];
    $data = Product::where('name', '=', 'Bag Product')
        ->project($projectArray)
        ->get();

Mongoplayground

0

There are 0 best solutions below