2017-07-04 66 views
0

我想获得包含所有打折产品的目录。Mongodb:汇总数据并在每个元素上应用函数

2个文件:

/* Catalog schema */ 
{ 
    Catalog: { 
    products: [{ 
     type: ObjectId, 
     ref: 'Product' 
    }], 
    discount: { 
    global: { type: Number, default: 0 }, 
    categories: [{ 
     codeCategory: String, 
     discount: Number 
    }] 
} 
} 


/* Product schema */ 
{ 
    reference: { 
    type: String, 
    index: true, 
    unique: true 
    }, 
    url_photo: { 
    type: String, 
    default: 'http://localhost:3001/app/img/no-picture.jpg' 
    }, 
    category: { 
    type: ObjectId, 
    ref: 'Category' 
    }, 
    short_description: String, 
    long_description: String, 
    price: Number, 
    information: String 
} 

的折扣适用于从目录中的每个产品,我怎么能做出蒙戈查询目录中得到所有产品与应用的折扣?

我可以直接查询有这个结果吗?

我已经检查了聚合,但我是新的,我看不到我怎么做到这一点。

谢谢

+0

凡存储的文件?在同一个集合中?您使用了哪些驱动程序,例如猫鼬,pymongo等?如果我不得不猜测,我会说你正在用猫鼬做一个Node应用程序。 – dasdachs

+0

目录,产品和类别是分离的集合。我正在使用猫鼬。你猜对了,它是节点应用程序。 – stephane

+0

为什么在Catalog Schema中有两个'discounts'? – dasdachs

回答

2

您可以在3.4管道中使用下面的聚合。

$lookup拉动产品数据类别在catalog.products路径并使用$map申请折扣,每个产品的价格,包括所有类似如图所示为information领域的产品领域。 $addFields以折扣价格覆盖产品阵列。

如果在目录中找到匹配的产品类别,请添加类别等级折扣。使用$indexOfArray找到匹配的类别的指标,一旦发现,使用$arrayElemAt找到索引处的类别,然后投射折扣金额,否则为0

[ 
    { 
    "$lookup": { 
     "from": "products", 
     "localField": "catalog.products", 
     "foreignField": "_id", 
     "as": "catalog.products" 
    } 
    }, 
    { 
    "$addFields": { 
     "catalog.products": { 
     "$map": { 
      "input": "$catalog.products", 
      "as": "product", 
      "in": { 
      "price": { 
       "$multiply": [ 
       "$$product.price", 
       { 
        "$add": [ 
        "$catalog.discount.global", 
        { 
         "$let": { 
         "vars": { 
          "index": { 
          "$indexOfArray": [ 
           "$catalog.discount.categories.codeCategory", 
           "$$product.category" 
          ] 
          } 
         }, 
         "in": { 
          "$cond": [ 
          { 
           "$eq": [ 
           "$$index", 
           -1 
           ] 
          }, 
          0, 
          { 
           "$let": { 
           "vars": { 
            "categorydisc": { 
            "$arrayElemAt": [ 
             "$catalog.discount.categories", 
             "$$index" 
            ] 
            } 
           }, 
           "in": "$$categorydisc.discount" 
           } 
          } 
          ] 
         } 
         } 
        } 
        ] 
       } 
       ] 
      }, 
      "information": "$$product.information" 
      } 
     } 
     } 
    } 
    } 
] 
+0

你好Veeram,谢谢你的答案,我明白您的要求是全球折扣,如果有类别折扣,我如何将product.category与折扣类别进行匹配? – stephane

+0

不客气。我已经添加了针对类别级别折扣进行调整的逻辑。 – Veeram

+0

Wonderfull !!! 对于像我这样的新手mongo,你只是吓到我了!但我明白更多我怎么想到用mongo构建一个请求你真棒!在您的请求中存储像您所做的那样的价值会更好吗?或者只是在需要发送目录时提出请求以获得折扣价值?我的问题是基于perf – stephane