0

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..

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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
Thus because there are multiple documents in eventList array, use aggregation pipeline to achieve the result
@skylerByun - Please see the modified answer using aggregation pipeline

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.