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?
2 Answers
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();
}
Comments
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.*;
7 Comments
Marcolia
is it possible to sort descending?
prasad_
Yes, change the code from
sort(ascending("arrSize")) to sort(descending("arrSize")). I changed the code in the answer, too.Marcolia
i got this message "pipeline can not contain a null value"
prasad_
I got the correct output, and no errors (tried just now). Are you able to compile the code?
Marcolia
and this "The method ascending(String) is undefined for the type MYCLASS"
|