Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to get product collection in Magento 2

Vinh Jacker | 03-17-2025

How to get product collection in Magento 2

Magento 2 is one of the most popular eCommerce platforms available today, and its ability to handle complex and large-scale product catalogs makes it a favorite among merchants. Understanding how to get product collection in Magento 2 is crucial for developers who want to manipulate product data for various tasks, such as building custom reports, integrating third-party services, or improving website performance.

In this guide, we will explore the step-by-step process of retrieving product collections in Magento 2, including best practices, code snippets, and common issues to avoid.

Learn more: Get product collection by category ID in Magento 2

What is a Product Collection in Magento 2?

In Magento 2, a product collection refers to a set of products that can be filtered, sorted, and loaded based on specific criteria. This allows developers to work with groups of products rather than individual items, making it easier to apply changes or retrieve information in bulk.

Product collections are used throughout the Magento system, especially in frontend displays like category pages, search results, and product listing pages. Understanding how to retrieve and manipulate these collections is essential for customizing the eCommerce experience.

Why You Might Need to Get a Product Collection

Getting a product collection can be necessary for various reasons, including:

  • Customizing product displays on the frontend
  • Building advanced product filters based on attributes like price, category, or stock status
  • Integrating with third-party APIs for marketing or inventory management
  • Creating custom reports for business analytics

By learning how to fetch product collections, developers can unlock new possibilities for customizing Magento 2 stores and improving overall functionality.

Setting Up Your Development Environment

Before diving into the code, ensure you have a properly configured Magento 2 development environment. You’ll need access to:

  • A local or remote Magento 2 installation
  • PHPStorm or any other preferred IDE
  • Magento 2 CLI tools for clearing caches and reindexing
  • A basic understanding of PHP and Magento’s Object Manager

With everything in place, you’ll be ready to start working with product collections.

How to Get Product Collection in Magento 2

There are different ways to get product collection in Magento 2. This post will guide you in retrieving a product collection in Magento 2 using various conditions such as loading, filtering, and sorting, which will help you effectively manage and display products within your Magento store.

  • Load product collection
  • Get product collection
  • Filter product collection
  • Sort of product collection

Load product collection in Magento 2

Load product collection with Mageplaza_HelloWorld module

Step 1: Declare in Mageplaza_HelloWorld Block

You will use a block class of the module Mageplaza_HelloWorld, then possibly inject the object of \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory in the constructor of the module’s block class.

app/code/Mageplaza/HelloWorld/Block/HelloWorld.php
<?php
namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
        array $data = []
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
    }
    
    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(3); // fetching only 3 products
        return $collection;
    }
}
?>

Note: You can request the number of the product collection, which is a limited or unlimited number. While implementing this function, you will need to extend the code based on the requirement.

Step 2: Display the product collection in phtml file

Print out the product collection in phtml file with the below code:

$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    print_r($product->getData());     
    echo "<br>";
}

Now, you can get the data of each product in the requested collection.

Load Product Collection with Specific Attribute

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect(['name','sku']);
$collection->setPageSize(3);
foreach ($collection as $product) {
    print_r($product->getData());
}

Load Product Collection with All Attribute

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3);
foreach ($collection as $product) {
    print_r($product->getData());
}

Get Product Collection in Magento 2

By Multiple Categories

$categories = [1,2,3]; //category ids array
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => $categories]);
return $collection;

By Specific Category

$categoryId = '1';
$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;

By Product Type

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('type_id', ['eq' => 'simple']);
$collection->getSelect()->order('created_at', \Magento\Framework\DB\Select::SQL_DESC);
$collection->getSelect()->limit(10);
return $collection;

NOTE: You can also use the following values for type_id to apply filters for different product types.

  • Simple - Filter of a simple product
  • Configurable - Filter of configurable product
  • Grouped - Filter of a grouped product
  • Virtual - Filter of virtual product
  • Bundle - Filter of bundle product

By Store ID

$storeid = 1;
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addStoreFilter($storeid);
return $collection;

By Website IDs

$website_ids = [1,2];
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addStoreFilter($storeid);
$collection->addWebsiteFilter($websiteIds);
return $collection;

Filter Product Collection in Magento 2

There are various filters available for product collections. Let’s go through each of them individually below.

Is Equal to

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['eq' => 1]);

Is Not Equal to

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['neq' => 1]);

Greater than

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['gt' => 100]);

Greater than Equal to

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['gteq' => 100]);

Less than

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['lt' => 100]);

Less than Equal to

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['lteq' => 100]);

Like

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('sku', ['like' => '%Bag%']);

Not Like

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('sku', ['nlike' => '%Bag%']);

In Array

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', ['in' => [1,2]]);

Not in Array

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', ['nin' => [1,2]]);

NULL

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('description',  ['null' => true]);

Not NULL

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('description',  ['notnull' => true]);

Sort Product Collection in Magento 2

Similar to filters, there are various ways to sort your product collection. Let’s explore them below.

Order by ASC

$collection = $this->productCollectionFactory->create();
$collection->getSelect->order('sku', 'ASC');

Or

$collection = $this->productCollectionFactory->create();
$collection->setOrder('sku', 'ASC');

Order by DESC

$collection = $this->productCollectionFactory->create();
$collection->getSelect->order('sku', 'DESC');

Or

$collection = $this->productCollectionFactory->create();
$collection->setOrder('sku', 'DESC');

Set Limit Product Collection

$collection = $this->productCollectionFactory->create();
$collection->setPageSize(50)->load();

Set Limit Product Collection with Current Page

$collection = $this->productCollectionFactory->create();
$collection->setPageSize(50)->setCurPage(2)->load();

Count Product Collection

$collection = $this->productCollectionFactory->create();
echo $collection->count();

Group by Product Collection

$collection = $this->productCollectionFactory->create();
$collection->getSelect()->group('entity_id');
$collection = $this->productCollectionFactory->create();
echo $collection->getSelect()->__toString();

Common Issues When Working with Product Collections

While retrieving product collections in Magento 2 is straightforward, there are some common pitfalls to watch out for:

  • Performance issues: Loading too many products or attributes can slow down your site. Always limit the number of products and select only necessary attributes.
  • Caching: Remember to clear Magento’s cache after making changes to product collections or custom modules.
  • Reindexing: If you’ve made changes to product data, make sure to run php bin/magento indexer:reindex to update the indexes.

Avoiding these common mistakes will ensure that your product collections perform optimally.

Best Practices for Getting Product Collections

To summarize, here are some best practices to follow when retrieving product collections in Magento 2:

  • Always use Dependency Injection to inject the ProductCollectionFactory.
  • Filter and sort collections based on your needs to reduce the load on the database.
  • Limit the number of products and select only necessary attributes.
  • Make sure to handle caching and reindexing to avoid issues with product data.

Following these best practices will help you write clean, efficient code that performs well.

Conclusion

Understanding how to get product collection in Magento 2 is an essential skill for developers working with the platform. By mastering product collections, you can manipulate product data effectively, improve site performance, and provide custom functionality to meet specific business needs. Whether you’re creating custom product filters, integrating with third-party systems, or building tailored frontend experiences, product collections are a versatile and powerful tool in Magento 2 development.

By following the steps outlined in this guide and adhering to best practices, you’ll be able to get and manipulate product collections with ease. Happy coding!

x
    Jacker

    Jacker is the Chief Technology Officer (CTO) at Mageplaza, bringing over 10 years of experience in Magento, Shopify, and other eCommerce platforms. With deep technical expertise, he has led numerous successful projects, optimizing and scaling online stores for global brands. Beyond his work in eCommerce development, he is passionate about running and swimming.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services