I want to add category id filter to Magento 2 product collection but it doesn't filter the collection in required manner. I am trying in below way:

$collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')
            ->joinField('category_id', 'catalog_category_product', 'category_id', 'product_id=entity_id', null, 'left')
            ->addFieldToFilter('category_id', ['nin' => 25]);

I don't want any product from category id 25 to be included in collection.


You can use

addCategoriesFilter(['nin' => $categories]);


$collection = $this->_productCollectionFactory->create()
$collection->addCategoriesFilter(['nin' => 25]);
  • I tried it, doesn't work. – Himmat Paliwal May 12 '17 at 6:32
  • I found an issue at my end, my code was also working fine but same product id was assigned to another category too. So it was loading in collection. Anyways thanks for your support @userpk :) – Himmat Paliwal May 12 '17 at 6:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.