首页 > 解决方案 > mongodb 2级聚合

问题描述

我有 3 个相互引用的集合,这样

A -> B -> C

我想在与 B 匹配并从 B 到 C 后过滤数据

集合 1

Products: [{
_id:ObjectId(),
name:"product1",
productCatalogue:[reference to productCatalogue collection]
},....]

收藏 2

productCatalogue: [{
_id:ObjectId(),
name:"catelgoue1",
category:{
  cat:[reference to category table],
  sub1:[reference to category table],
  sub2:[reference to category table]
}
},...]

集合 3

category: [{
  _id:ObjectId(),
  name:"cat1",
  type:"parent"
},....]

我想过滤数据,以便使用聚合过滤具有目录:catelgoue1 和类别:cat1 的产品。

标签: mongodbmongooseaggregation

解决方案


您可以在每次查找 $match 示例代码之前使用:

const orderProcess = await Order.aggregate([
{
    $match: {
        userId: userId
    }
},
{
    $lookup: {
        from: "products",
        localField: "product_id",
        foreignField: "_id",
        as: "product",                 
    }
},
{
    $unwind: "$product"
},
{
    $lookup: {
        from: "prices",
        localField: "product_id", // $product._id => like top lookup data
        foreignField: "productId", // $product._id => like top lookup data
        as: "price"
    },
},
{
    $unwind: "$price"
},
{
    $project:{
        // response all item
    }
}])

推荐阅读