I have a mongo database with 4 documents. These documents contain an array with different length. I want to sort the documents by the length of their array in java with the mongodb driver. How would i do that?
Asked
Active
Viewed 680 times
0
-
check this https://stackoverflow.com/questions/9040161/mongo-order-by-length-of-array – BENMOHAMED Charfeddine Dec 09 '19 at 09:23
2 Answers
2
You can do it in two ways:
1) Add an additional field to your document which will contain the size of this array. And then sort the documents by this field.
2) Using the aggregation framework. Unwind the array and then group it and additionally sum the elements in the array. And then finally sorting it by the size.
public void myFunction(){
List<AggregationOperation> aggregationOperations = new ArrayList<>();
aggregationOperations.add(Aggregation.unwind("myArrayField"));
aggregationOperations.add(Aggregation.group("_id").push("myArrayField").as("myArrayField").sum("1").as("size")
.first("fieldToPreserve").as("fieldToPreserve")); //preserve fields from first document
aggregationOperations.add(Aggregation.sort(Sort.Direction.DESC,"size"));
mongoTemplate.aggregate(Aggregation.newAggregation(aggregationOperations), "MyCollection", MyCollection.class).getMappedResults();
}

Sagar Ahuja
- 637
- 10
- 10
1
The aggregation query for this sorts the documents by the array size, desscending:
db.test.aggregate( [
{ $addFields: { arrSize: { $size: "$arr" } } },
{ $sort: { arrSize: -1 } }
] )
The Java code using driver version 3.9.0:
Bson addFiledsStage = addFields(new Field<Document>("arrSize", new Document("$size", "$arr")));
Bson sortStage = sort(descending("arrSize"));
List<Bson> pipeline = Arrays.asList(addFiledsStage, sortStage);
List<Document> results = new ArrayList<>();
collection.aggregate(pipeline).into(results);
results.forEach(System.out::println);
The required imports for the above code:
import org.bson.Document;
import org.bson.conversions.Bson;
import static com.mongodb.client.model.Sorts.*;
import static com.mongodb.client.model.Aggregates.*;
import com.mongodb.client.model.Field;
import java.util.*;

prasad_
- 12,755
- 2
- 24
- 36
-
-
Yes, change the code from `sort(ascending("arrSize"))` to `sort(descending("arrSize"))`. I changed the code in the answer, too. – prasad_ Dec 09 '19 at 13:09
-
-
I got the correct output, and no errors (tried just now). Are you able to compile the code? – prasad_ Dec 09 '19 at 13:17
-
and this "The method ascending(String) is undefined for the type MYCLASS" – Marcolia Dec 09 '19 at 13:17
-
Do you have all the imports? What is the driver and Java versions you are using? – prasad_ Dec 09 '19 at 13:18
-
Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/203918/discussion-between-marcolia-and-prasad). – Marcolia Dec 09 '19 at 13:19