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.

1 Answer 1


You can use

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


$collection = $this->_productCollectionFactory->create()
$collection->addCategoriesFilter(['nin' => 25]);
  • I tried it, doesn't work. May 12, 2017 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 :) May 12, 2017 at 6:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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