如何在mongo db中按字符串类型的日期属性对记录进行排序

时间:2016-01-26 04:30:18

标签: node.js mongodb express

我在mongo db中有如下记录:

 [{
    "_id" : ObjectId("56840939e41a0038122b04c1"),
    "sudentName":"xxx",
    "payments" : [
            {
                    "paymentAmount" : 5000,
                    "paymentMode" : "Education",
                    "paidBy" : "Parent1",
                    "paymentDate" : "30-12-2015",
                    "paymentId" : ObjectId("5684097be41a0038122b04c2")
            },
            {
                    "paymentAmount" : 6000,
                    "paymentMode" : "Transport",
                    "paidBy" : "Parent1",
                    "paymentDate" : "30-12-2015",
                    "paymentId" : ObjectId("56840a54e41a0038122b04c3")
            },
            {
                    "paymentAmount" : 5000,
                    "paymentMode" : "Education",
                    "paidBy" : "Srinivas Nalla",
                    "paymentDate" : "19-01-2016",
                    "paymentId" : ObjectId("569e65cee51c46601bce3e1b")
            },
            {
                    "paymentAmount" : 5000,
                    "paymentMode" : "Education",
                    "paidBy" : "nalla",
                    "paymentDate" : "26-01-2016",
                    "paymentId" : ObjectId("56a6ea344d3111180cdeef5b")
            }
    ]
 }]

我使用以下查询对结果进行分组,使用studentName和最近的paymentDate对paymentAmount进行分组:

 db.students.aggregate([{$match:{studentName:"XXX"}},{$unwind:"$payments"},{$group:{_id:"$payments.paymentMode",paidDate:{$max:"$payments.paymentDate"},paidAmount:{$sum:"$payments.paymentAmount"}}}]);

此查询的付款日期错误结果如下:

   { "_id" : "Transport", "paidDate" : "30-12-2015", "paidAmount" : 6000 }
   { "_id" : "Education", "paidDate" : "30-12-2015", "paidAmount" : 15000 }

但我希望结果如下:

    { "_id" : "Transport", "paidDate" : "30-12-2015", "paidAmount" : 6000 }
    { "_id" : "Education", "paidDate" : "26-01-2016", "paidAmount" : 15000 }

我不明白查询中的问题在哪里。我使用$ max运算符作为payemtDate列。

任何人都可以帮助我吗?

0 个答案:

没有答案