Sort submatrices in summary result

I have three documents:

{ "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" } 

and I need to group them throughout the day, so I:

 { "$match": { "id_user": "t57092501745ad6285ac58c22" } }, { "$sort": { "date": -1 } }, { "$group": { "_id": { $dayOfYear: "$date" }, "data": { "$push": { "id_user": "$id_user", "name": "$name", "date": "$date", "text": "$text" }, }, } } 

and the result:

 { { _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" }] } } 

and that’s fine, but the order is not what I need:

 { Day #1 }, { Day #3, Day #2 } 

if I change sort to { "date": 1 } , I can invert the order of the two groups, as follows:

 { Day #3, Day #2 }, { Day #1 } 

but I don’t know how to also change the order inside the submatrix to get the correct value:

 { Day #1 }, { Day #2, Day #3 } 

What is the right way?

+5
source share
1 answer

If you want the elements in the "array" to be in ascending order, your $sort order is wrong and you need to undo it. Also, the output from $group as a "document" is in no way ordered. Therefore, if you need a specific order, you actually need $sort on the returned _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 } } ] 

Then both orders are correct.

+3
source

Source: https://habr.com/ru/post/1247791/


All Articles