0

我有一组如下所示的文档:

{
  user: "D1D2A08B-7242-4415-BA4F-442B18DBD2ED-2463-00000074A82D0518",
  language: "Cantonese",
  imageFileName: "01D28C90-DB71-40E2-96A2-A934ABC54815-2695-0000043BD1ECAB22",
  audioFileName: "76CD717B-1A57-412C-8973-3518D72B45AD-8996-000008855B90D78A",
  date: ISODate("2013-04-04T18:24:25.753Z"),
  correct: 1,
  _id: ObjectId("515dc559cd9d87de5a000018")
}

以下查询执行我期望按 ISODate 元素排序的聚合:

var getUserStats = function(user, language, callback) {
    var guessCollection = db.collection('Guesses');
    guessCollection.aggregate(
  { $match: {
    user: user,
    language: language,
  }},
  { $sort: {
    date: 1
  }},
  { $project : {
        user : 1,
        language : 1,
        year : { $year: '$date' },
        month : { $month: '$date' },
        day : { $dayOfMonth: '$date'},
        correct : 1,
        guesses : 1
    } },
  { $group : {
        _id : { year: "$year", month: "$month", day: "$day" },
        correct : { $sum : "$correct" },
        guesses: { $sum : 1 }
    } }
, function(err, result){
    console.log(result);
    callback(err, result);
});

这是一个示例查询结果:

[{
        _id: {
            year: 2013,
            month: 6,
            day: 8
        },
        correct: 11,
        guesses: 17
    }, {
        _id: {
            year: 2013,
            month: 6,
            day: 7
        },
        correct: 11,
        guesses: 15
    }, {
        _id: {
            year: 2013,
            month: 6,
            day: 5
        },
        correct: 35,
        guesses: 48
    }, {
        _id: {
            year: 2013,
            month: 6,
            day: 6
        },
        correct: 69,
        guesses: 96
    }, {
        _id: {
            year: 2013,
            month: 5,
            day: 25
        },
        correct: 2,
        guesses: 3
        ...

如您所见,查询的结果不是按日期排序的。有人可以建议我可能做错了什么吗?

4

1 回答 1

0

一个组可以是无序的。您可以做的正确排序是_id在分组后对它进行另一种排序。

于 2013-06-09T20:39:23.883 回答