Group objects and then sort these groups using a single query

80 Views Asked by At

I need to implement a mongo query that forms 2 group depending if the avatarUrl is non null and then sorts these groups by lastName.

Here is how the collection looks like:

{
    "lastName": "Bradley",
    "avatarUrl": "http://...",
},
{
    "lastName": "Bradley",
    "avatarUrl": null,
},
{
    "lastName": "Chateau",
    "avatarUrl": null,
}
{
    "lastName": "Ezekiel",
    "avatarUrl": "http://...",
},
{
    "lastName": "Zerox",
    "avatarUrl": "http://...",
}

And I need this query to return the following list:

{
    "lastName": "Bradley",
    "avatarUrl": "http://...",
},
{
    "lastName": "Ezekiel",
    "avatarUrl": "http://...",
},
{
    "lastName": "Zerox",
    "avatarUrl": "http://...",
}
{
    "lastName": "Bradley",
    "avatarUrl": null,
},
{
    "lastName": "Chateau",
    "avatarUrl": null,
}

As you can see it is split in two groups and every group is sorted by alphabetical order.

Is there a way to do so using a single mongo query?

I tried using this:

getCollection().find().sort({ "lastName": 1, "avatarUrl": -1}).toList()

But it clearly doesn't work.

0

There are 0 best solutions below