Marcolia
Marcolia

Reputation: 40

Sort by array length in java mongodb

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?

Upvotes: 0

Views: 767

Answers (2)

prasad_
prasad_

Reputation: 14287

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

Upvotes: 1

Sagar Ahuja
Sagar Ahuja

Reputation: 717

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();
}

Upvotes: 2

Related Questions