定義
insert1 つ以上のドキュメントをコレクションに挿入し、ステータス ドキュメントを返します。MongoDB ドライバーの挿入メソッドは、内部的にこのコマンドを使用します。
Tip
In
mongosh, this command can also be run through thedb.collection.insertOne()anddb.collection.insertMany()helper methods.Helper methods are convenient for
mongoshusers, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.次の値を返します。 操作のステータスを含むドキュメント。詳細については出力を参照してください。
互換性
このコマンドは、次の環境でホストされている配置で使用できます。
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
注意
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
このコマンドの構文は、次のとおりです。
db.runCommand( { insert: <collection>, documents: [ <document>, <document>, <document>, ... ], ordered: <boolean>, maxTimeMS: <integer>, writeConcern: { <write concern> }, bypassDocumentValidation: <boolean>, comment: <any> } )
コマンドフィールド
このコマンドは、次のフィールドを使用します。
フィールド | タイプ | 説明 |
|---|---|---|
| string | ターゲット コレクションの名前。 |
| 配列 | 名前付きコレクションに挿入する 1 つ以上のドキュメントの配列。 |
| ブール値 | 任意. |
| non-negative integer | 任意。 時間制限をミリ秒単位で指定します。 MongoDB は、 |
| ドキュメント | 任意.書込み保証 (write concern) を指定します。デフォルトの書込み保証 (write concern) を使用する場合は省略します。 トランザクションで実行される場合、操作の書込み保証 (write concern)を明示的に設定しないでください。トランザクションで書込み保証を使用するには、「トランザクション書込み保証」を参照してください。 |
| ブール値 | |
| any | 任意。このコマンドに添付するユーザー指定のコメント。設定すると、このコメントは以下の場所にこのコマンドの記録と合わせて表示されます。
コメントには、有効な BSON 型(string, integer, object, array など)を使用できます。 |
動作
サイズ制限
すべての documents 配列要素の合計サイズは、最大 BSON ドキュメント サイズを超えてはなりません。
documents配列内のドキュメントの合計数は、最大バルク サイズを超えてはなりません。
スキーマ検証
The insert command adds support for the bypassDocumentValidation option, which lets you bypass schema validation when inserting or updating documents in a collection with validation rules.
トランザクション
insert can be used inside distributed transactions.
重要
ほとんどの場合、分散トランザクションでは 1 つのドキュメントの書き込み (write) よりもパフォーマンス コストが高くなります。分散トランザクションの可用性は、効果的なスキーマ設計の代わりにはなりません。多くのシナリオにおいて、非正規化されたデータモデル(埋め込みドキュメントと配列)が引き続きデータやユースケースに最適です。つまり、多くのシナリオにおいて、データを適切にモデリングすることで、分散トランザクションの必要性を最小限に抑えることができます。
トランザクションの使用に関するその他の考慮事項(ランタイム制限や oplog サイズ制限など)については、「本番環境での考慮事項」も参照してください。
トランザクションでのコレクション作成
トランザクションがクロスシャード間書き込みトランザクション(write transaction)でない場合に、分散トランザクション内にコレクションとインデックスを作成できます。
トランザクションにないコレクションに挿入を指定すると、MongoDB は暗黙的にコレクションを作成します。
書込み保証とトランザクション
トランザクションで実行される場合、操作の書込み保証 (write concern)を明示的に設定しないでください。トランザクションで書込み保証を使用するには、「トランザクション書込み保証」を参照してください。
不正確な挿入
挿入中にサーバー エラーが発生した場合でも、一部のドキュメントは挿入されている可能性があります。
挿入を成功させると、システムはコレクションに挿入されたドキュメントの数を返します。レプリカセットの状態が変化して挿入操作が中断された場合でも、システムはドキュメントの挿入を続行できます。その結果、報告するドキュメント数が実際に挿入された数より少なくなる場合があります。
例
単一ドキュメントのインサート
usersコレクションにドキュメントを挿入します。
db.runCommand( { insert: "users", documents: [ { _id: 1, user: "abc123", status: "A" } ] } )
この操作を実行すると次のドキュメントが返されます。
{ "ok" : 1, "n" : 1 }
Bulk Insert
usersコレクションに 3 つのドキュメントを挿入します。
db.runCommand( { insert: "users", documents: [ { _id: 2, user: "ijk123", status: "A" }, { _id: 3, user: "xyz123", status: "P" }, { _id: 4, user: "mop123", status: "P" } ], ordered: false, writeConcern: { w: "majority", wtimeout: 5000 } } )
この操作を実行すると次のドキュメントが返されます。
{ "ok" : 1, "n" : 3 }
Insert with の使用 bypassDocumentValidation
スキーマ検証 validationActions が error に設定されている場合、検証に失敗したドキュメントに対しては挿入コマンドがエラーを返します。検証ルールに違反するドキュメントを挿入するには、bypassDocumentValidation: true を設定します。
statusフィールドの検証ルールを使用してuserコレクションを作成します。
検証ルールは、ステータスが "Unknown" または "Incompleted" でなければならないことを検証します。
db.createCollection("users", { validator: { status: { $in: [ "Unknown", "Incomplete" ] } } })
検証ルールに違反するドキュメントを挿入します。
db.runCommand({ insert: "users", documents: [ {user: "123", status: "Active" } ] })
挿入は書き込みエラーメッセージを返します。
{ n: 0, writeErrors: [ { index: 0, code: 121, errInfo: { failingDocumentId: ObjectId('6197a7f2d84e85d1cc90d270'), details: { operatorName: '$in', specifiedAs: { status: { '$in': [Array] } }, reason: 'no matching value found in array', consideredValue: 'Active' } }, errmsg: 'Document failed validation' } ], ok: 1 }
bypassDocumentValidation: trueを設定して挿入を再実行します。
db.runCommand({ insert: "users", documents: [ {user: "123", status: "Active" } ], bypassDocumentValidation: true })
操作は成功しました。
スキーマの検証ルールに違反するドキュメントを確認するには、validate コマンドを使用します。
出力
返されるドキュメントには、次のフィールドのサブセットが含まれます。
insert.writeErrorsAn array of documents that contains information regarding any error encountered during the insert operation. The
writeErrorsarray contains an error document for each insert that errors.各エラー ドキュメントには以下のフィールドが含まれます。
insert.writeConcernError書込み保証 (write concern) に関連するエラーを説明するドキュメント。
バージョン 7.0.6 での変更:
(also available in 6.0.14 and 5.0.30): When
insertexecutes onmongos, write concern errors are always reported, even when one or more write errors occur. In previous releases, the occurrence of write errors could cause theinsertto not report write concern errors.writeConcernErrorドキュメントには次のフィールドが含まれています。insert.writeConcernError.errInfo.writeConcern対応する操作に使用される書込み保証 (write concern) オブジェクトです。書込み保証 (write concern) オブジェクト フィールドの詳細については、「書込み保証 (write concern) の仕様」を参照してください。
書込み保証 (write concern) オブジェクトには、書込み保証 (write concern) のソースを示す以下のフィールドも含むことができます。
insert.writeConcernError.errInfo.writeConcern.provenance書込み保証 (write concern) が発生した場所を示す文字列値です(書込み保証 (write concern)
provenanceと呼ばれます)。次の表は、このフィールドに指定できる値とその意味を示しています。出所説明clientSupplied書き込み保証(write concern)がアプリケーションで指定されました。
customDefault書込み保証 (write concern) は、カスタム定義されたデフォルト値に基づきます。
setDefaultRWConcernを参照してください。getLastErrorDefaults書込み保証 (write concern) は、レプリカセットの
settings.getLastErrorDefaultsのフィールドに基づきます。implicitDefault他の書き込み保証(write concern)が一切指定されていない状態で、サーバーから発生した書き込み保証。
以下は、単一ドキュメントの挿入が成功した場合の出力例です。
{ ok: 1, n: 1 }
1 つのドキュメントの挿入に成功し、2 つ目のドキュメントの挿入に失敗した場合の出力例を次に示します。
{ "ok" : 1, "n" : 1, "writeErrors" : [ { "index" : 1, "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.users.$_id_ dup key: { : 1.0 }" } ] }