Mongodb聚合,无法在日期字段上进行排序

时间:2013-07-02 19:45:01

标签: node.js mongodb mongoose

数据:

{ 
  "properties" : { 
    "user" : ObjectId("51d3053627f4169a52000005"), 
    "createdOn" : ISODate("2013-07-02T18:00:03.841Z")
  }, 
  "_id" : ObjectId("51d31a87716fb81a58000003"), 
  "geometry" : { 
    "type" : "Point", 
    "coordinates" : [ 10, 10 ] 
  } 
},{ 
  "properties" : { 
    "user" : ObjectId("51d3053627f4169a52000005"), 
    "createdOn" : ISODate("2013-07-02T18:23:03.841Z")
  }, 
  "_id" : ObjectId("51d31a87716fb81a58000003"), 
  "geometry" : { 
    "type" : "Point", 
    "coordinates" : [ 20, 20 ] 
  } 
}

我正在尝试以下查询:

db.locations.aggregate(
  { $group: { 
    _id: "$properties.user", 
    locations: { 
      $push: {
        location: {geometry: "$geometry", properties: "$properties"} 
      } 
    }
  }}, 
  { $sort: { "properties.createdOn": 1 }}
);

无论我改变排序标志(1 / -1)的哪个方向,我的结果顺序都不会改变。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

$group之后,您的管道文档只包含$group中定义的字段,因此properties.createdOn操作不存在$sort

$sort移到管道中的$group之前:

db.locations.aggregate(
  { $sort: { "properties.createdOn": 1 }},
  { $group: { 
    _id: "$properties.user", 
    locations: { 
      $push: {
        location: {geometry: "$geometry", properties: "$properties"} 
      } 
    }
  }}
);