2016-06-10 123 views
-1
Sale.aggregate({ 
    $match: filter 
}, { 
    $group: { 
    "_id": { 
     "store_id": "$store_id", 
     //"created_on": { $dateToString: { format: "%Y-%m-%d", date: "$strBillDate" } } 
    }, 
    month: { 
     $month: "$strBillDate" 
    }, 
    store_id: { 
     $first: "$store_id" 
    }, 
    strBillAmt: { 
     $sum: "$strBillAmt" 
    }, 
    strBillNumber: { 
     $sum: 1 
    } 
    } 
}) 

而是日期,我需要集團銷售收入月,集團如何銷售在幾個月的NodeJS如何根據nodejs中的月份對數據進行分組?

+0

顯示你的數據庫結構。 – Shrabanee

+0

store_id:{type:String},strBillNumber:{type:String},strBillDate:{type:Date},strBillAmt:{type:Number}, –

回答

0

我用了一個projection首先在總量鏈提取月度和年度值,之後做了分組:

<doc-name>.aggregate([ 
    { $project: 
     { _id: 1, 
      year: { $year: "$date" }, 
      month: { $month: "$date"}, 
      amount: 1 
     } 
    }, 
    { $group: 
     { _id: { year: "$year", month: "$month" }, 
      sum: { $sum: "$amount" } 
     } 
    }]) 

我也與你的模型的嘗試:

var testSchema = mongoose.Schema({ 
    store_id: { type: String }, 
    strBillNumber: { type: String }, 
    strBillDate: { type: Date }, 
    strBillAmt: { type: Number } 
}); 

var Test = mongoose.model("Test", testSchema); 

創建一些測試數據:

var test = new Test({ 
    store_id: "1", 
    strBillNumber: "123", 
    strBillDate: new Date("2016-04-02"), 
    strBillAmt: 25 
}); 
var test2 = new Test({ 
    store_id: "1", 
    strBillNumber: "124", 
    strBillDate: new Date("2016-04-01"), 
    strBillAmt: 41 
}); 
var test3 = new Test({ 
    store_id: "3", 
    strBillNumber: "125", 
    strBillDate: new Date("2016-05-13"), 
    strBillAmt: 77 
}); 

運行查詢:

Test.aggregate([ 
    { $project: 
     { store_id: 1, 
      yearBillDate: { $year: "$strBillDate" }, 
      monthBillDate: { $month: "$strBillDate" }, 
      strBillAmt: 1 
     } 
    }, 
    { $group: 
     { _id: {yearBillDate: "$yearBillDate", monthBillDate:"$monthBillDate"}, 
      sum: { $sum: "$strBillAmt" } 
     } 
    } 
    ], function(err, result) { 
     console.log(err, result)}); 

,並得到一個合理的結果: result of aggregate query

+0

對我無效 –

+0

您是否因爲數據模型? – FlorianE

+0

不是模型的bcoz –

相關問題