簡體   English   中英

mongodb中如何使用聚合和匹配?

[英]How use aggregate and match in mongodb?

我有兩個集合 ProductInventories 和 ProductDetails。 ProductInventories 有一個 prodId,它連接到 ProductDetails 的 id。 我想獲得所有僅活躍的產品。

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

我正在使用此代碼來獲取所有數據,但我希望有一個條件,即它將返回 isActicve = True 的項目。 我只是使用過濾器 function 過濾所有活動數據。 我想學習如何使用聚合和匹配。

您可以首先根據 prodId 字段使用從 ProductInventories 到 ProductDetails 的查找聚合,然后使用字段 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/

這是我更新的代碼,它現在可以工作了。 也感謝您幫助@smitha t m。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM