Sorting in query "WITH" scope

To make a clear picture of my problem here is the working original code:

MATCH (u:User)-[:GROUPUSER]-(g:Group) WHERE id(u)=1
WITH g,
[(g)-[:GROUPUSER]-(us:User) | id(us)] AS userIds
RETURN id(g) as id, g.name as name, userIds ORDER BY name

The result is the group's id, name and the users' ids, and the problem is the users' ids is not sorted, but I want to sort them somehow like ORDER BY id(us), but I could not figure out what is the solution.

If you have APOC Procedures, you can use apoc.coll.sort() on the collection:
https://neo4j.com/docs/labs/apoc/current/data-structures/collection-list-functions/

If not, then you'll need to avoid the pattern comprehension and instead do another MATCH, then sort, then collect:

MATCH (u:User)-[:GROUPUSER]-(g:Group)
WHERE id(u)=1
MATCH (g)-[:GROUPUSER]-(us:User)
WITH g, id(us) as userId
ORDER BY userId
WITH g, collect(userId) as userIds
RETURN id(g) as id, g.name as name, userIds 
ORDER BY name
1 Like