JavaでMongoDBコレクション内の複数のドキュメントを一括更新する方法
MongoDBでは、updateMany()メソッドを使うことで、指定した条件に一致するコレクション内のすべてのドキュメントを一度に更新できます。1件だけを更新するupdateOne()とは異なり、フィルターに合致した全件が更新対象になる点が大きな特徴です。
基本構文
db.COLLECTION_NAME.updateMany(<filter>, <update>)
Javaから利用する場合は、com.mongodb.client.MongoCollectionインターフェースが同名のupdateMany()メソッドを提供しています。第1引数に検索条件(フィルター)、第2引数に更新内容を渡すだけで、複数ドキュメントの一括更新が可能です。
Javaでの実装例
以下のサンプルでは、まず3件のドキュメントをコレクションに挿入し、その後「cityがDelhi」であるドキュメントをすべて「Vijayawada」へ一括更新しています。
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
public class UpdatingMultipleDocuments {
public static void main(String args[]) {
// Mongoクライアントの作成
MongoClient mongo = new MongoClient("localhost", 27017);
// データベースへの接続
MongoDatabase database = mongo.getDatabase("myDatabase");
// コレクションオブジェクトの取得
MongoCollection<Document> collection = database.getCollection("myCollection");
// 挿入用ドキュメントの準備
Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad");
Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Delhi");
Document document3 = new Document("name", "Rahim").append("age", 30).append("city", "Delhi");
// 作成したドキュメントを一括挿入
List<Document> list = new ArrayList<Document>();
list.add(document1);
list.add(document2);
list.add(document3);
collection.insertMany(list);
System.out.println("List of the documents: ");
FindIterable<Document> iterDoc = collection.find();
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// cityが「Delhi」のドキュメントをすべて更新
Bson filter = new Document("city", "Delhi");
Bson newValue = new Document("city", "Vijayawada");
Bson updateOperationDocument = new Document("$set", newValue);
collection.updateMany(filter, updateOperationDocument);
System.out.println("Document update successfully...");
System.out.println("List of the documents after update");
iterDoc = collection.find();
it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
実行結果
List of the documents:
Document{{_id=5e88a61fe7a0124a4fc51b2c, name=Ram, age=26, city=Hyderabad}}
Document{{_id=5e88a61fe7a0124a4fc51b2d, name=Robert, age=27, city=Delhi}}
Document{{_id=5e88a61fe7a0124a4fc51b2e, name=Rahim, age=30, city=Delhi}}
Document update successfully...
List of the documents after update
Document{{_id=5e88a61fe7a0124a4fc51b2c, name=Ram, age=26, city=Hyderabad}}
Document{{_id=5e88a61fe7a0124a4fc51b2d, name=Robert, age=27, city=Vijayawada}}
Document{{_id=5e88a61fe7a0124a4fc51b2e, name=Rahim, age=30, city=Vijayawada}}
解説のポイント
- $set演算子: 更新内容を
$setでラップすると、ドキュメント全体を置き換えることなく、指定したフィールドだけを部分的に更新できます。 - 戻り値の確認: updateMany()はUpdateResultを返すため、getMatchedCount()やgetModifiedCount()で一致件数・更新件数をプログラムから確認できます。
- ヘルパークラスの活用: この例ではBsonフィルターを手動で組み立てていますが、インポート済みの
Filters.eq()やUpdates.set()を使うと、より簡潔かつ型安全に記述できます。 - 注意点: 新しいバージョンのMongoDB Javaドライバーでは
MongoClientのコンストラクタは非推奨のため、MongoClients.create()の使用が推奨されます。
-
JavaでMongoDBコレクションからデータを取得する際にレコード数を制限する方法
MongoDBのコレクションからレコードを取得する際、limit()メソッドを使用することで、結果として返されるレコードの件数を制限できます。大量のデータが格納されたコレクションから必要な分だけ効率よく取り出したい場合に非常に便利な機能です。 limit()メソッドの基本構文 db.COLLECTION_NAME.find().limit(取得したいレコード数) シェル上では上記のように記述します。JavaのMongoDBドライバ(ライブラリ)にも同名のlimit()メソッドが用意されており、find()メソッドの実行結果に対して、必要なレコード数を表す整数値を引数として渡して呼び出すことで、
-
JavaでMongoDBからデータを取得する際にドキュメントをスキップする方法
MongoDBコレクションからレコードを取得する際、skip()メソッドを使うと、検索結果の先頭から指定した件数のドキュメントを読み飛ばすことができます。Webアプリケーションのページネーション(ページ送り)機能などを実装する際に非常に便利なメソッドです。基本構文db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)JavaのMongoDBライブラリにも同名のskip()メソッドが用意されています。find()メソッドの実行結果に対してこのメソッドを呼び出し、引数として「スキップしたいレコード数」を表す整数値を渡すだけで、簡単にドキュメントをス