var reportSchema = new Schema({
session_id: {type: Schema.Types.ObjectId, ref: 'Session'},
learner_id: {type: Schema.Types.ObjectId, ref: 'User'},
text: {type: String},
});
Report.aggregate(
[
{$group: {
_id: '$created_at',
}},
{$sort: {"created_at": -1}},
{"$limit": 10}
],
function(err, result) {
Ids = [];
for (var i in result)
Ids.push(result[i]._id);
ApiResponse.send(res, {success: true, data: result});
}
);
`
{
success: true
data: [6]
0: {
_id: "2015-04-14T11:54:20.517Z"
}-
1: {
_id: "2015-04-01T11:54:15.802Z"
}-
2: {
_id: "2015-04-01T11:54:29.941Z"
}-
3: {
_id: "2015-05-14T11:52:28.811Z"
}-
4: {
_id: "2015-04-02T12:54:46.903Z"
}-
5: {
_id: "2015-04-01T11:52:22.642Z"
}-
-
message: ""
}
{
success: true
data: [6]
0: {
_id: "2015-04-01"
}-
1: {
_id: "2015-04-02"
}-
2: {
_id: "2015-04-14"
}-
-
message: ""
}
我在创建的日期做了分组,这是isoDate,我想仅根据日期而不是日期和时间进行分组。
答案 0 :(得分:1)
使用以下代码段
Report.aggregate([
{ "$group": {
"_id":{
"$concat": [
{ "$substr": [ { "$year": "$created_at" }, 0, 4 ] },
'-',
{ "$cond": [
{ "$lt": [ { "$month": "$created_at" }, 10 ] },
{ "$concat": [
"0",
{ "$substr": [ { "$month": "$created_at" }, 0, 2 ] },
]},
{ "$substr": [ { "$month": "$created_at" }, 0, 2 ] }
]},
'-',
{ "$cond": [
{ "$lt": [ { "$dayOfMonth": "$created_at" }, 10 ] },
{ "$concat": [
"0",
{ "$substr": [ { "$dayOfMonth": "$created_at" }, 0, 2 ] },
]},
{ "$substr": [ { "$dayOfMonth": "$created_at" }, 0, 2 ] }
]}
]
},
date: {$max: '$created_at'},
}},
{ "$sort":{ "date" :-1 }}
]);
//输出如下 -
{
"result" : [
{
"_id" : "2015-02-27",
"date" : ISODate("2015-02-27T21:46:06.080Z")
},
{
"_id" : "2015-02-22",
"date" : ISODate("2015-02-22T19:08:53.964Z")
},
{
"_id" : "2015-02-21",
"date" : ISODate("2015-02-21T12:57:16.887Z")
},
],
"ok" : 1
}
由于