我有三份文件:
{
"id_user": "t57092501745ad6285ac58c22",
"name": "Day #1",
"date": {
"$date": "2016-04-21T20:50:00.190Z"
},
"text": "My text"
}
{
"id_user": "t57092501745ad6285ac58c22",
"name": "Day #2",
"date": {
"$date": "2016-04-22T20:50:00.190Z"
},
"text": "My text"
}
{
"id_user": "t57092501745ad6285ac58c22",
"name": "Day #3",
"date": {
"$date": "2016-04-22T20:51:00.190Z"
},
"text": "My text"
}
我需要将这些分组当天,所以我这样做:
{
"$match": {
"id_user": "t57092501745ad6285ac58c22"
}
}, {
"$sort": {
"date": -1
}
}, {
"$group": {
"_id": {
$dayOfYear: "$date"
},
"data": {
"$push": {
"id_user": "$id_user",
"name": "$name",
"date": "$date",
"text": "$text"
},
},
}
}
结果是:
{
{
_id: 113,
data: [{
"id_user": "t57092501745ad6285ac58c22",
name: "Day #1",
date: "2016-04-22T20:51:00.190Z",
text: "My text"
}]
}, {
_id: 114,
data: [{
"id_user": "t57092501745ad6285ac58c22",
name: "Day #3",
date: "2016-04-23T20:51:00.190Z",
text: "My text"
}, {
"id_user": "t57092501745ad6285ac58c22",
name: "Day #2",
date: "2016-04-23T20:50:00.190Z",
text: "My text"
}]
}
}
没关系,但订单不是我需要的:
{ Day #1 }, { Day #3, Day #2 }
如果我将sort
更改为{ "date": 1 }
我可以按照这样的方式反转2组的顺序:
{ Day #3, Day #2 }, { Day #1 }
但是我不知道如何更改子数组中的顺序,以获得正确的:
{ Day #1 }, { Day #2, Day #3 }
正确的方法是什么?
答案 0 :(得分:3)
如果您希望“数组”中的项目处于“升序”顺序,那么您的$sort
订单错误,您需要撤消它。此外,$group
作为“文档”的输出也不以任何方式排序。因此,如果您需要特定订单,那么您还需要在返回的$sort
上实际_id
:
[
{ "$match": {
"id_user": "t57092501745ad6285ac58c22"
}},
{ "$sort": { "date": 1 } }
{ "$group": {
"_id": { "$dayOfYear": "$date" },
"data": {
"$push": {
"id_user": "$id_user",
"name": "$name",
"date": "$date",
"text": "$text"
}
}
}},
{ "$sort": { "_id": 1 } }
]
然后两个订单都是正确的