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

ドキュメントの更新

collection.updateOne() を使用して単一のドキュメントを更新できます使用して複数のドキュメントを挿入できます。 updateOne()メソッドは フィルター ドキュメント と アップデート ドキュメントを受け入れます。 クエリがコレクション内のドキュメントを照合する場合、メソッドは更新ドキュメントからの更新を照合するドキュメントのフィールドと値に適用します。 更新ドキュメントには、照合対象に対する変更をメソッドに指示する 演算子が含まれています。

updateOne()メソッドの 2 番目のパラメータとして渡されるoptionsオブジェクトを使用して、さらにクエリ オプションを指定できます。 フィルターに一致するドキュメントがない場合に新しいドキュメントを作成するには、 upsertオプションをtrueに設定します。 詳しくは、 updateOne() API ドキュメント を参照してください。

updateOne() は、実行中にエラーが発生した場合に例外をスローします。更新ドキュメントで不変フィールド _id の値を指定すると、メソッドは例外をスローします。更新ドキュメントにユニークインデックスのルールに違反する値が含まれている場合、メソッドは duplicate key error 例外をスローします。

注意

アプリケーションで更新後にドキュメントが必要な場合は、 collection.findOneAndUpdate() 。メソッド。これはupdateOne() と似たインターフェースですが、元のドキュメントまたは更新されたドキュメントも返します。

次の例では、ドキュメント フィールドの更新値を指定する $set 更新演算子を使用しています。更新演算子の詳細については、「MongoDB 更新演算子のリファレンス ドキュメント」を参照してください。

注意

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

1// Update a document
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 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Create a filter for movies with the title "Random Harvest"
16 const filter = { title: "Random Harvest" };
17
18 /* Set the upsert option to insert a document if no documents match
19 the filter */
20 const options = { upsert: true };
21
22 // Specify the update to set a value for the plot field
23 const updateDoc = {
24 $set: {
25 plot: `A harvest of random numbers, such as: ${Math.random()}`
26 },
27 };
28
29 // Update the first document that matches the filter
30 const result = await movies.updateOne(filter, updateDoc, options);
31
32 // Print the number of matching and modified documents
33 console.log(
34 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`,
35 );
36 } finally {
37 // Close the connection after the operation completes
38 await client.close();
39 }
40}
41// Run the program and print any thrown errors
42run().catch(console.dir);
1// Update a document
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
10// Define the Movie interface
11interface Movie {
12 plot: string;
13 title: string;
14}
15
16async function run() {
17 try {
18 const database = client.db("sample_mflix");
19 const movies = database.collection<Movie>("movies");
20
21 /* Update a document that has the title "Random Harvest" to have a
22 plot field with the specified value */
23 const result = await movies.updateOne(
24 { title: "Random Harvest" },
25 {
26 $set: {
27 plot: `A harvest of random numbers, such as: ${Math.random()}`,
28 },
29 },
30 /* Set the upsert option to insert a document if no documents
31 match the filter */
32 { upsert: true }
33 );
34
35 // Print the number of matching and modified documents
36 console.log(
37 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`
38 );
39 } finally {
40 // Close the connection after the operation completes
41 await client.close();
42 }
43}
44// Run the program and print any thrown errors
45run().catch(console.dir);

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

1 document(s) matched the filter, updated 1 document(s)

戻る

更新と置換操作