2016-06-15 5 views
1

私には以下の文書が含まれています。私は内部の顧客数を集計するために集計を使用したいが、いくつか問題がある。私は総行を得ることができますが、(一意の)総数の顧客は取得できません。MongoDB集約 - 個別のカウント固有の要素

[{ 
    _id: "n001", 
    channel: "Kalipare", 
    trans: { 
     _id: "trans001", 
     customerID: "customerCXLA93", 
     customerName: "Kalipare Fried Chicked" 
    } 
}, { 
    _id: "n002", 
    channel: "Kalipare", 
    trans: { 
     _id: "trans002", 
     customerID: "customerCXLA93", 
     customerName: "Kalipare Fried Chicked" 
    } 
}, { 
    _id: "n003", 
    channel: "Kalipare", 
    trans: { 
     _id: "trans003", 
     customerID: "customerPWR293", 
     customerName: "Kalipare Papabun" 
    } 
}, { 
    _id: "n004", 
    channel: "Kalipare", 
    trans: { 
     _id: "trans004", 
     customerID: "customerPWR293", 
     customerName: "Kalipare Papabun" 
    } 
}, { 
    _id: "n005", 
    channel: "Tumpakrejo", 
    trans: { 
     _id: "trans005", 
     customerID: "customerPWR293", 
     customerName: "Tumpakrejo Big Burger" 
    } 
}] 

これは私のコードです。どのように

db.col.aggregate([ 
    { $group: { 
     _id: "$channel", 
     totalRow: { $sum: 1 } 
    } } 
]) 

私は、ユニークな顧客をカウントし、このようなデータを生成するために行う必要があります。独自の顧客数を取得するための

[{ 
    _id: "Kalipare", 
    totalRow: 4, 
    totalCustomer: 2 
}, { 
    _id: "Tumpakrejo", 
    totalRow: 1, 
    totalCustomer: 1 
}] 

答えて

1

$addToSet演算子を使用して、グループのパイプライン内で一意の顧客IDのセットを作成する必要があります。配列を取得したら、$size演算子を$projectパイプライン内のパイプラインで使用すると、ユニークな数が得られます。

db.col.aggregate([ 
    { 
     "$group": { 
      "_id": "$channel", 
      "totalRows": { "$sum": 1 }, 
      "totalCustomer": { "$addToSet": "$trans.customerID" } 
     } 
    }, 
    { 
     "$project": { 
      "totalRows": 1, 
      "totalCustomers": { "$size": "$totalCustomer" } 
     } 
    } 
]) 

が出力:以下アグリゲーションパイプラインを実行

はあなたの望ましい結果得られます

{ 
    "result" : [ 
     { 
      "_id" : "Tumpakrejo", 
      "totalRows" : 1, 
      "totalCustomers" : 1 
     }, 
     { 
      "_id" : "Kalipare", 
      "totalRows" : 4, 
      "totalCustomers" : 2 
     } 
    ], 
    "ok" : 1 
} 
+1

をどうもありがとうございました! – nvl