Kael
Kael

Reputation: 928

Multiple sorting in aggregate with mongo

When I use a multiple sorting in aggregate method with mongo, results aren't sorting in the right way. This is my query :

db.MyCollection.aggregate(
{
    "$unwind": "$objects"
},
{
    "$lookup": {
        "from": "CollectionA",
        "localField": "objects.itemId",
        "foreignField": "_id",
        "as": "itemOne"
    }
},
{
    "$lookup": {
        "from": "CollectionB",
        "localField": "user_id",
        "foreignField": "id",
        "as": "users"
    }
},
{
    "$lookup": {
        "from": "CollectionC",
        "localField": "objects.itemName",
        "foreignField": "name",
        "as": "itemTwo"
    }
},
{
    "$addFields": {
        "item": {
            "$arrayElemAt": [
                "$itemOne",
                0
            ]
        },
        "user": {
            "$arrayElemAt": [
                "$users",
                0
            ]
        },
        "itemP": {
            "$arrayElemAt": [
                "$itemTwo",
                0
            ]
        }
    }
},
{
    "$addFields": {
        "itemName": {
            "$ifNull": [
                "$item.name",
                "$objects.itemName"
            ]
        },
        "userName": {
            "$concat": [
                "$user.firstname",
                " ",
                "$user.lastname"
            ]
        }
    }
},
{
    "$match": {
        "client_id": 2
    }
},
{
    "$skip": 1
},
{
    "$limit": 10
},
{
    "$project": {
       "date": "$objects.date",
       "state": "$objects.state"
    }
},
{
    "$sort": { 
        "objects.state": 1,
        "objects.date": 1,
    }
}

)

To precise: "date" field is Date type and "state" field is number type. If I use only one sort : result order is correct. But if I use 2 sorts, results are not order correctly. Have you got any ideas, why ?

Upvotes: 1

Views: 2407

Answers (1)

Kael
Kael

Reputation: 928

As @Neil Lunn says : They don't sort correctly because you renamed the fields in $project. So it should be { $sort: { state: 1, date: 1 } }

Upvotes: 1

Related Questions