skyler Byun
skyler Byun

Reputation: 1

mongoose sort by value of multiple objects in array

We have a problem while finding sorted data of mongoDB. Here is our data. There is userData with array 'eventList'.

[
 {
        "_id": "5a55eb107d4e4d5531d790e9",
        "id": "[email protected]",
        "intro": null,
        "name": "aaa",
        "eventList": [
            {
                "eventId": "5a2e18fa787af15faad72e5b",
                "title": "abc",
                "joinDate": "2018-01-12T00:17:33+09:00",
                "point": 0
            },
            {
                "eventId": "5a5486b9067610a13c4d401b",
                "title": "bcd",
                "joinDate": "2018-01-12T12:15:01+09:00",
                "point": 100
            }
        ]
    },
    {
        "_id": "5a5719520d76a14727a0c709",
        "id": "[email protected]",
        "intro": null,
        "name": "bbb",
        "eventList": [
            {
                "eventId": "5a2e18fa787af15faad72e5b",
                "title": "abc",
                "joinDate": "2018-01-11T16:59:16+09:00",
                "point": 12
            }
        ]
    },
    {
        "_id": "5a57193f99e37347212c33f8",
        "id": "[email protected]",
        "name" : "ccc",
        "eventList": [
            {
                "eventId": "5a2e18fa787af15faad72e5b",
                "title": "abc",
                "joinDate": "2018-01-11T16:58:57+09:00",
                "point": 3
            }
        ]
    }
]

I'd like to sort this documents by "point" values having title "abc" in userList array. How should I build query for this?

I made query for this

User.find({"eventList.eventId" : {eventId}}).sort({"eventList.point":-1})

the result is a-b-c but I think that should be b-c-a

How should I fix this? ;( Thank you..

Upvotes: 0

Views: 988

Answers (1)

Clement Amarnath
Clement Amarnath

Reputation: 5466

Using Aggregation pipeline we can do this,

$unwind to unwind the documents in eventList array

$match to find the matching documents

$sort to sort the documents

db.collection_name.aggregate([
   {$unwind:"$eventList"},
   {$match:{"eventList.title":"abc"}}, 
   {$sort:{"eventList.point":-1}}
]);

For sorting the documents in Ascending order use 1 and for descending order use -1

Upvotes: 1

Related Questions