Skip to content

Support for sorting simple arrays (integers/strings) with SortArray (Fixes #4929) #4943

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2067,5 +2067,27 @@ public SortArray by(Sort sort) {
protected String getMongoMethod() {
return "$sortArray";
}

/**
* Sort the array elements by their values in ascending order.
* Suitable for arrays of simple types (e.g., integers, strings).
*
* @return new instance of {@link SortArray}.
* @since 4.x (TBD)
*/
public SortArray byValueAscending() {
return new SortArray(append("sortBy", 1));
}

/**
* Sort the array elements by their values in descending order.
* Suitable for arrays of simple types (e.g., integers, strings).
*
* @return new instance of {@link SortArray}.
* @since 4.x (TBD)
*/
public SortArray byValueDescending() {
return new SortArray(append("sortBy", -1));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,26 @@ void sortByWithFieldRef() {
assertThat(ArrayOperators.arrayOf("team").sort(Sort.by("name")).toDocument(Aggregation.DEFAULT_CONTEXT))
.isEqualTo("{ $sortArray: { input: \"$team\", sortBy: { name: 1 } } }");
}

@Test // GH-4929
public void sortArrayByValueAscending() {
Document result = ArrayOperators.SortArray.sortArrayOf("numbers").byValueAscending().toDocument(Aggregation.DEFAULT_CONTEXT);
Document expected = new Document("$sortArray", new Document("input", "$numbers").append("sortBy", 1));
assertThat(result).isEqualTo(expected);
}

@Test // GH-4929
public void sortArrayByValueDescending() {
Document result = ArrayOperators.SortArray.sortArrayOf("numbers").byValueDescending().toDocument(Aggregation.DEFAULT_CONTEXT);
Document expected = new Document("$sortArray", new Document("input", "$numbers").append("sortBy", -1));
assertThat(result).isEqualTo(expected);
}

@Test // GH-4929
public void sortArrayByPropertyUnchanged() {
Document result = ArrayOperators.SortArray.sortArrayOf("items")
.by(Sort.by(Sort.Direction.ASC, "price")).toDocument(Aggregation.DEFAULT_CONTEXT);
Document expected = new Document("$sortArray", new Document("input", "$items").append("sortBy", new Document("price", 1)));
assertThat(result).isEqualTo(expected);
}
}