MongoTemplateでSpringBootを使用してMongoDBの結果を並べ替える

Aug 16 2020

目標

このクエリが欲しいのですが:

db.getCollection("employees").find().sort({
  hire_date: 1
}).limit(10)

SpringBootでMongoTemplateを使用して記述されています。

リサーチ

私は例えばのような分類について多くの投稿やサイトを見てきました

  • https://www.baeldung.com/java-mongodb-aggregations
  • Spring + MongoDB-MongoTemplate +基準クエリ
  • SpringMongoDBクエリの並べ替え

試み

私は多くの方法を試しましたが、どうすればこれを行うことができるのかまだわかりません。私が試したことのいくつかを以下に示します。

@Service
public class MongoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public Document simpleQuery() {

        // 1st
        mongoTemplate.aggregate(Arrays.asList(
                sort(Sorts.ascending("hire_date")),
                limit(10)
        ));

        // 2nd
        mongoTemplate.findAll(Employee.class).sort(new BasicDBObject("hire_date", 1));

        // 3rd
        mongoTemplate.findAll(Employee.class).sort((o1, o2) -> o1.getHire_date() > o2.getHire_date());

        // and more...
    }
}

解決策は、クエリ自体と同じように非常に単純かもしれませんが、これらはそのような理由での私の最初のステップです。これについて助けてくれてありがとう。

回答

1 varman Aug 17 2020 at 00:22

これを試して、

Aggregation aggregation = Aggregation.newAggregation(
    sort(Sort.Direction.ASC, "hire_date"),
    limit(10)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(Employee.class), Object.class).getMappedResults();
Gibbs Aug 17 2020 at 00:23

あなたは以下のようにすることができます。

  1. クエリ部分が必要です
//As you need to match all
Query query = new Query()
  1. 並べ替えオプションを追加する必要があります
//You need to use Sort class with sorting order, field name to be used for sorting
query.with(new Sort(Sort.Direction.ASC, "hire_date"));
  1. ページネーションオプションを追加する必要があります
final Pageable pageableRequest = PageRequest.of(0, 10);
query.with(pageableRequest);
  1. モデルを追加する必要があります
mongoTemplate(query, Employee.class)

サンプル参照

別の有用な答え