Overview
このガイドでは、 Rubyドライバーを使用して挿入操作を実行し、 MongoDBコレクションにドキュメントを追加する方法を学習できます。
挿入操作は 、1 つ以上の ドキュメント をMongoDBコレクションに挿入します。 次の方法を使用して、挿入操作を実行できます。
insert_one
: 単一のドキュメントを挿入するinsert_many
: 1 つ以上のドキュメントを挿入する
サンプル データ
このガイドの例では、 Atlasサンプルデータセット の sample_restaurants
データベースの restaurants
コレクションを使用します。Rubyアプリケーションからこのコレクションにアクセスするには、Atlas クラスターに接続する Mongo::Client
オブジェクトを作成し、次の値を database
変数と collection
変数に割り当てます。
database = client.use('sample_restaurants') collection = database[:restaurants]
MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。
_id フィールド
MongoDB コレクションでは、各ドキュメントに一意のフィールド値を持つ_id
フィールドが含まれている必要があります。
MongoDB では、このフィールドは次の 2 つの方法で管理できます。
各ドキュメントの
_id
フィールドを自分で設定し、各値が一意であることを確認します。ドライバーがドキュメント
_id
フィールドごとに一意のBSON::ObjectId
値を自動的に生成できるようにします。
一意性を保証できない限り、ドライバーに_id
値を自動的に生成させることをお勧めします。
注意
重複した _id
値はユニークインデックス制約に違反するため、ドライバーはエラーを返します。
_id
フィールドの詳細については、 マニュアルの 「 一意なインデックス 」MongoDB Server のガイドを参照してください。
ドキュメント構造とルールの詳細については、MongoDB Server マニュアルのドキュメントガイド を参照してください。
1つのドキュメントの挿入
MongoDBコレクションに単一のドキュメントを追加するには、insert_one
メソッドを呼び出し、挿入するドキュメントを渡します。
次の例では、 restaurants
コレクションにドキュメントを挿入します。
document = { name: 'Neighborhood Bar & Grill', borough: 'Queens' } collection.insert_one(document)
複数のドキュメントの挿入
MongoDBコレクションに複数のドキュメントを追加するには 、insert_many
メソッドを呼び出して、挿入するドキュメントのリストを渡します。
次の例では、 restaurants
コレクションに 2 つのドキュメントを挿入しています。
documents = [ { name: 'Metropolitan Cafe', borough: 'Queens' }, { name: 'Yankee Bistro', borough: 'Bronx' } ] collection.insert_many(documents)
挿入動作の変更
挿入操作を構成するオプションを設定するには、Hash
オブジェクトをinsert_one
メソッドのパラメーターとして渡します。オプションを指定しない場合、ドライバーはデフォルト設定で挿入操作を実行します。
次の表では、 insert_one
操作を構成するために設定できるオプションについて説明します。
オプション | 説明 |
---|---|
| Instructs the driver whether to ignore document-level validation. For more information,
see Schema Validation in the MongoDB Server manual. Defaults to false . |
| Sets a comment to attach to the operation. For more information, see the insert command
fields guide in the MongoDB Server manual. |
| Sets the session to use for the operation. To learn more about sessions, see
Client Sessions and Causal Consistency Guarantees
in the MongoDB Server manual. |
| Sets the write concern for the operation. For more information, see the
Write Concern guide in the MongoDB Server manual. |
メソッド呼び出しのパラメーターとして Hash
を渡すことで、insert_many
メソッドで上記の設定を設定できます。ordered
オプションを使用して、ドライバーがMongoDBにドキュメントを挿入する順序を指定することもできます。
例
次のコードでは、insert_many
メソッドを使用して、3 つの新しいドキュメントをコレクションに挿入します。bypass_document_validation
オプションが有効になっているため、この挿入操作はドキュメントレベルの検証をバイパスします。
documents = [ { name: 'Cloudy Day', borough: 'Brooklyn' }, { name: 'Squall or Shine', borough: 'Staten Island' } { name: 'Rose Field', borough: 'Queens' } ] options = { bypass_document_validation: true } collection.insert_many(documents, options)
API ドキュメント
このガイドで説明されているメソッドの詳細については、次の API ドキュメントを参照してください。