1

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.

Ashh
  • 44,693
  • 14
  • 105
  • 132
Baptiste Arnaud
  • 2,522
  • 3
  • 25
  • 55
  • Possible dupe of https://stackoverflow.com/questions/31084446/how-can-i-sort-into-that-nulls-are-last-ordered-in-mongodb – s7vr Nov 07 '18 at 13:57

0 Answers0