0

I have two collection ProductInventories and ProductDetails. The ProductInventories has a prodId that is connected to the id of ProductDetails. I want to get all the product that is Active only.

const products = await ProductInventory.find().populate({
    path: 'prodId',
    model: ProductDetails,
    populate: { path: 'category', select: 'category_name', model: Category },
  });

I'm using this code to get all the data, but I want to have a condition that it will return the item that is isActicve = True. I'm just using a filter function to filter all active data. I want to learn how to use aggregate and match.

2 Answers 2

0

You can first use the lookup aggregation from ProductInventories to ProductDetails based on the prodId field, then do a match aggregation with field isActive = true

db.ProductInventories.aggregate([
   { 
    $lookup: { 
        from: "ProductDetails",
        localField: "prodId",
        foreignField: "id",
        as: "product_details"
    },
    $match: {
        isActive: true
    }
}
])

Refer https://docs.mongodb.com/manual/reference/operator/aggregation/match/ https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

0
0

This is my updated code and its working now. Thanks also for helping @smitha t m.

 const products = await ProductInventory.aggregate([
    {
      $lookup: {
        from: 'productdetails',
        localField: 'prodId',
        foreignField: '_id',
        as: 'product',
      },
    },
    {
      $unwind: '$product',
    },
    {
      $match: { 'product.isActive': true },
    },
  ]);

Your Answer

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

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