Docs Menu
Docs Home
/ / /
Node.js ドライバー
/ /

複数のドキュメントの更新

コレクション.updateMany() メソッドを使用して複数のドキュメントをアップデートできますupdateMany() メソッドは、フィルタードキュメントとアップデートドキュメントを受け入れます。クエリがコレクション内のドキュメントと一致する場合、メソッドは、アップデートドキュメントからのアップデートを一致するドキュメントのフィールドと値に適用します。アップデートドキュメントでは、アップデート演算子がドキュメント内のフィールドを変更する必要があります。

updateMany()メソッドの 3 番目のパラメータで渡されるoptionsオブジェクトで、さらにオプションを指定できます。 詳しくは 、 updateMany() API ドキュメント を参照してください。

注意

この例を使用して、MongoDB のインスタンスに接続し、サンプルデータを含むデータベースと交流できます。MongoDB インスタンスへの接続とサンプルデータセットの読み込みの詳細については、 使用例ガイドを参照してください。

1/* Update multiple documents */
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async function run() {
11 try {
12 // Get the "movies" collection in the "sample_mflix" database
13 const database = client.db("sample_mflix");
14 const movies = database.collection("movies");
15
16 // Create a filter to update all movies with a 'G' rating
17 const filter = { rated: "G" };
18
19 // Create an update document specifying the change to make
20 const updateDoc = {
21 $set: {
22 random_review: `After viewing I am ${
23 100 * Math.random()
24 }% more satisfied with life.`,
25 },
26 };
27 // Update the documents that match the specified filter
28 const result = await movies.updateMany(filter, updateDoc);
29 console.log(`Updated ${result.modifiedCount} documents`);
30 } finally {
31 // Close the database connection on completion or error
32 await client.close();
33 }
34}
35run().catch(console.dir);
1/* Update multiple documents */
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string.
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10enum Rating {
11 G = "G",
12 PG = "PG",
13 PG_13 = "PG-13",
14 R = "R",
15 NR = "NOT RATED",
16}
17
18// Create a Movie interface
19interface Movie {
20 rated: Rating;
21 random_review?: string;
22}
23
24async function run() {
25 try {
26 // Get the "movies" collection in the "sample_mflix" database
27 const database = client.db("sample_mflix");
28 const movies = database.collection<Movie>("movies");
29
30 // Update all documents that match the specified filter
31 const result = await movies.updateMany(
32 { rated: Rating.G },
33 {
34 $set: {
35 random_review: `After viewing I am ${
36 100 * Math.random()
37 }% more satisfied with life.`,
38 },
39 }
40 );
41 console.log(`Updated ${result.modifiedCount} documents`);
42 } finally {
43 // Close the database connection on completion or error
44 await client.close();
45 }
46}
47run().catch(console.dir);

前の例を実行すると、次の出力が表示されます。

Updated 477 documents

戻る

ドキュメントの更新