简体   繁体   English

在java mongodb中按数组长度排序

[英]Sort by array length in java mongodb

I have a mongo database with 4 documents.我有一个包含 4 个文档的 mongo 数据库。 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.我想使用 mongodb 驱动程序按 java 中数组的长度对文档进行排序。 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. 1) 向您的文档添加一个附加字段,该字段将包含此数组的大小。 And then sort the documents by this field.然后按此字段对文档进行排序。

2) Using the aggregation framework. 2)使用聚合框架。 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:使用驱动程序版本 3.9.0 的Java 代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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