I am using following function to get product collection from a category with it's id.
public function getProductCollection($categoryId)
{
$category = $this->_categoryFactory->create()->load($categoryId);
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;
}
This returns all the products in the category and products in subcatgories. I've enabled anchor for the category. I have found this solution for magento 1 which suggests to disable anchor for the category. But I need it be enabled so as to implement layered navigation.
Any idea on how we can get products only in the category excluding those in subcategories?