AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

未定義の値

このガイドでは、ドライバーがundefined値を直列化する方法を制御する方法を学習できます。 デフォルトでは、ドライバーは書込み操作中にundefined値をnull値として直列化します。

直列化中にドライバーがundefined値を持つフィールドを無視するようにするには、 ignoreUndefinedの設定をtrueに設定します。 この設定を指定すると、ドライバーはundefined値を持つフィールドを直列化しません。

次の例では、2 つのドキュメントを挿入しています。 最初の挿入操作では、 ignoreUndefined設定がtrueに設定されているため、ドライバーはその操作でsalesTaxフィールドを直列化しません。 2 番目の 操作では、 salesTaxフィールドにnull値を持つドキュメントが挿入されます。

await myColl.insertOne( { state: "Montana", salesTax: undefined, }, { ignoreUndefined: true }); await myColl.insertOne({ state: "New Hampshire", salesTax: undefined,});

ドキュメントは、 コレクションに次のように表示されます。

{ _id: ..., state: "Montana",},{ _id: ..., state: "New Hampshire", salesTax: null}

ignoreUndefined設定は次のレベルで指定できます。

  • クライアント レベル

  • データベース レベル

  • コレクション レベル

  • 操作レベル

ignoreUndefined設定は、それを指定したオブジェクト インスタンスの範囲と、そのインスタンスから作成された他のオブジェクトに自動的に適用されます。

たとえば、データベース オブジェクトをインスタンス化するときにignoreUndefined設定を設定すると、そのオブジェクトから作成されたすべてのコレクション インスタンスが 設定を継承します。 さらに、そのコレクション インスタンスで呼び出す操作も、 設定を継承します。

次の例では、 myDBデータベース オブジェクトからignoreUndefined設定を継承する検索とアップデートの操作を実行します。 この操作ではドライバーがgasTaxフィールドを無視するため、データは変更されません。

const myDB = client.db("test", { ignoreUndefined: true }); // The collection inherits the ignoreUndefined settingconst myColl = myDB.collection("states"); // Any write operation will not serialize undefined valuesawait myColl.findOneAndUpdate( { state: "Georgia" }, { $set: { gasTax: undefined } });

継承された設定を上書きするには、任意のレベルで再度ignoreUndefined設定を再度指定できます。

たとえば、コレクション オブジェクトでignoreUndefinedをtrueに設定すると、そのコレクションに対して実行する個々の書込み操作で 設定を上書きできます。

const myColl = myDB.collection("states", { ignoreUndefined: true }); // The insert operation will not serialize undefined valuesawait myColl.insertOne({ state: "South Dakota", capitalGainsTax: undefined,}); // The insert operation will serialize undefined valuesawait myColl.insertOne( { state: "Texas", capitalGainsTax: undefined }, { ignoreUndefined: false });