Javaを使ってMongoDBコレクションのドキュメントをソートする方法
MongoDBコレクションからレコードを取得する際、結果として得られるドキュメントを特定のフィールドの値に基づいて並べ替え(ソート)したいケースはよくあります。MongoDBではsort()メソッドを使用することで、検索結果を昇順または降順に簡単に並べ替えることができます。
基本構文
MongoDBシェルでの基本的な構文は以下のとおりです。キーの値に「1」を指定すると昇順、「-1」を指定すると降順になります。
db.COLLECTION_NAME.find().sort({KEY:1})Javaドライバでのsort()メソッドの使い方
JavaのMongoDBライブラリにも同名のsort()メソッドが用意されています。find()メソッドの実行結果に対してこのメソッドを呼び出し、引数としてソート対象のフィールド名と、昇順・降順のいずれかを指定します。
昇順・降順の指定には、com.mongodb.client.model.Sortsクラスのヘルパーメソッドが便利です。例えば、「age」フィールドを基準に昇順でソートする場合は次のように記述します。
sort(Sorts.ascending("age"))降順にしたい場合はSorts.descending("age")を使用します。また、複数のフィールドを組み合わせてソートすることも可能です。
サンプルコード
以下は、JavaでMongoDBのコレクションにドキュメントを挿入し、「age」フィールドを基準に昇順でソートして取得する完全なサンプルです。
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Sorts;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
public class SortingRecords {
public static void main( String args[] ) {
// MongoDBクライアントの作成
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// データベースへの接続
MongoDatabase database = mongo.getDatabase("myDatabase");
// コレクションオブジェクトの取得
MongoCollection<Document> collection = database.getCollection("students");
// 挿入するドキュメントの作成
Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad");
Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam");
Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi");
Document document4 = new Document("name", "Radha").append("age", 28).append("city", "Mumbai");
Document document5 = new Document("name", "Ramani").append("age", 45).append("city", "Pune");
// ドキュメントの一括挿入
List<Document> list = new ArrayList<Document>();
list.add(document1);
list.add(document2);
list.add(document3);
list.add(document4);
list.add(document5);
collection.insertMany(list);
System.out.println("Documents Inserted");
// コレクションオブジェクトの再取得
collection = database.getCollection("students");
// ageフィールドを基準に昇順ソートしてドキュメントを取得
FindIterable<Document> iterDoc =
collection.find().sort(Sorts.ascending("age"));
// 結果の表示
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}実行結果
上記のプログラムを実行すると、ドキュメントが「age」フィールドの値が小さい順(昇順)に並べ替えられて出力されます。
Documents Inserted
Document{{_id=5e88843d5c851b345fce2a33, name=Ram, age=26, city=Hyderabad}}
Document{{_id=5e88843d5c851b345fce2a34, name=Robert, age=27, city=Vishakhapatnam}}
Document{{_id=5e88843d5c851b345fce2a36, name=Radha, age=28, city=Mumbai}}
Document{{_id=5e88843d5c851b345fce2a35, name=Rhim, age=30, city=Delhi}}
Document{{_id=5e88843d5c851b345fce2a37, name=Ramani, age=45, city=Pune}}ポイントまとめ
- find()の結果に対してsort()をチェーンして呼び出すことでソートが可能。
- 昇順は
Sorts.ascending()、降順はSorts.descending()を使用。 - limit()やskip()など他のメソッドとも組み合わせて柔軟なデータ取得ができる。
-
JavaでMongoDBからデータを取得する際にドキュメントをスキップする方法
MongoDBコレクションからレコードを取得する際、skip()メソッドを使うと、検索結果の先頭から指定した件数のドキュメントを読み飛ばすことができます。Webアプリケーションのページネーション(ページ送り)機能などを実装する際に非常に便利なメソッドです。基本構文db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)JavaのMongoDBライブラリにも同名のskip()メソッドが用意されています。find()メソッドの実行結果に対してこのメソッドを呼び出し、引数として「スキップしたいレコード数」を表す整数値を渡すだけで、簡単にドキュメントをス
-
JavaでMongoDBデータベース内のすべてのコレクションを一覧表示する方法
MongoDBでは、show collections コマンドを使うことで、データベースに存在するすべてのコレクションの一覧を表示できます。 例 たとえば、MongoDBデータベースに以下のように3つのコレクションを作成したとします。 > use sampleDatabase switched to db sampleDatabase > db.createCollection(students) { ok : 1 } > db.createCollection(teachers) { ok : 1 } > db.createCollection(sample) { o