0

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?

1

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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.*;

7 Comments

is it possible to sort descending?
Yes, change the code from sort(ascending("arrSize")) to sort(descending("arrSize")). I changed the code in the answer, too.
i got this message "pipeline can not contain a null value"
I got the correct output, and no errors (tried just now). Are you able to compile the code?
and this "The method ascending(String) is undefined for the type MYCLASS"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.