2017-07-04 64 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