简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM