db.collection.aggregate([
{
$match : { filterQuery}
},
{
$addFields :{ “customGradeOrder” : { $indexOfArray: [ [“Gold”, “Silver”, “Bronze”] , “$grade” ] }}
},{$sort : { customGradeOrder : 1 } }
]);
Does mongo java driver Aggregates has any method to add fields with values resolved from index of array operator ?
Example ::
Student 1: Name grade A Silver
Student 2 : Name grade B Gold
Student 3: Name grade : C Bronze
The query is to query the student collection and get it sorted in specific value of grades of students (not in simple ascending or descending order.)
Output would be : B Gold A Silver C Bronze
CodePudding user response:
This works as well, apart from the solution you mentioned:
FindIterable<Document> result = collection.aggregate(Arrays.asList(new Document("$addFields",
new Document("customGradeOrder",
new Document("$indexOfArray", Arrays.asList(Arrays.asList("Gold", "Silver", "Bronze"), "$grade")))),
new Document("$sort",
new Document("customGradeOrder", 1L))));