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

EJSON.stringify()

EJSON.stringify()メソッドは、BSON 値を string に変換します。

EJSON.stringify() メソッドは、 BSONオブジェクトを入力と、出力stringの形式を制御するオプションの修飾子として受け取ります。

EJSON.stringify(BSON object, [replacer], [space], [options])

EJSON.stringify()メソッドには次のフィールドがあります:

フィールド
タイプ
必要性
説明

value

BSON オブジェクト

必須

オブジェクトEJSON.stringify()は変換されます

replacer

配列または関数

任意

出力を変更します。 値が存在するが、配列または関数でない場合、 EJSON.stringify()はすべてのドキュメント フィールドを返します。

replacer は、配列または関数にすることができます。

  • array: 出力に含めるドキュメントフィールドの配列。配列要素には、返されるJSON stringに含めるフィールド名を指定する必要があります。

  • function: key と value の2つのパラメーターを受け取る関数。key は、関数の this コンテキストを提供します。EJSONは変換されたvalueを返します。

    関数はオブジェクトごとに実行されます。 オブジェクト値は、関数の戻り値に置き換えられます。

    例については、「関数を使用して出力フィールドを変換する 」を参照してください。

spacer

整数または文字列

任意

出力のスペースを制御します。 spacerオプションのみを指定する場合は、 nullをreplacerのプレースホルダーとして使用します。

  • integer: 各レベルでインデントするスペースの数。最大値は 10 です。

  • string: 各レベルのインデントに使用する文字。このオプションでは、スペースまたはタブ以外の文字を使用すると、無効なJSONが生成されます。詳しくは、JSON.stringify() を参照してください

options

ブール値

任意

追加の構成オプション

  • relaxedデフォルトはtrue 。Extended JSON の緩和モードを有効にします。該当する場合、BSON 型情報を付加する代わりにネイティブ JSON 型を返します。

EJSON インターフェースは、インタラクティブなmongoshセッション内、または--evalを使用してシステム コマンドラインから呼び出すことができます。

対話型セッションから EJSON インターフェイスを呼び出します。

EJSON.stringify( db.sales.find().toArray(), null, 2 )

システム コマンドラインから EJSON インターフェイスを呼び出します。

mongosh --eval "EJSON.stringify( db.sales.find().toArray(), null, 2 )"

EJSON にドキュメントを渡す方法を制御するには、 mongoshカーソル メソッドイテレータのいずれかを使用します。

イテレータ
特性

ブロッキングは結果全体をバッファします

非ブロッキング、ドキュメントを 1 つずつ出力します

非ブロッキング、結果を手動で反復処理

これらの例を試すには、まずtestデータベースにsalesコレクションを作成します。

db.sales.insertMany( [ { custId: 345, purchaseDate: ISODate("2023-07-04"), quantity: 4, cost: Decimal128("100.60"), }, { custId: 346, purchaseDate: ISODate("2023-07-12"), quantity: 3, cost: Decimal128("175.45"), }, { custId: 486, purchaseDate: ISODate("2023-08-01"), quantity: 9, cost: Decimal128("200.53"), },] )

レベル間のインデントを増やすには、 spacingオプションを設定します。

EJSON.stringify( db.sales.findOne( { custId: 345 } ), null , 5 )

EJSON.stringify() は、各ドキュメント レベルの 5 つのスペースをインデントします。

{ "_id": { "$oid": "64da90c1175f5091debcab26" }, "custId": 345, "purchaseDate": { "$date": "2023-07-04T00:00:00Z" }, "quantity": 4, "cost": { "$numberDecimal": "100.60" }}

ドキュメント フィールドのサブセットを選択するには、配列を使用してreplaceオプションを設定します。

EJSON.stringify( db.sales.find().toArray(), [ "quantity", "cost" ] )

EJSON では、各ドキュメントに対してquantityとcostが形式されます。

[{"quantity":4,"cost":{}},{"quantity":3,"cost":{}},{"quantity":9,"cost":{}}]

この例ではspacingオプションが指定されていないため、EJSON は選択したフィールドを 1 行で返します。

フィールド値を変換するには、JavaScript 関数を使用してreplacerオプションを設定します。 例:

let queryResults = db.sales.find().toArray()let replacer = function( key, value ){ if ( key === '_id' ) { value = undefined; } if ( key === 'quantity' ) { value = 2 * value; } return value;} EJSON.stringify( queryResults, replacer, 3 )

関数は、入力オブジェクトに対して再帰的に実行されます。

出力例:

[ { "custId": 345, "purchaseDate": { "$date": "2023-07-04T00:00:00Z" }, "quantity": 8, "cost": { "$numberDecimal": "100.60" } }, { "custId": 346, "purchaseDate": { "$date": "2023-07-12T00:00:00Z" }, "quantity": 6, "cost": { "$numberDecimal": "175.45" } }, { "custId": 486, "purchaseDate": { "$date": "2023-08-01T00:00:00Z" }, "quantity": 18, "cost": { "$numberDecimal": "200.53" } }]

replacer関数は、 _idとquantityの 2 つのフィールドを更新します。

EJSON.stringify() は未定義の値を持つフィールドを無視するため、_id: undefined を設定すると出力stringから _id フィールドが削除されます。

この関数は、出力stringの quantity フィールドも変更します。 すべての quantity 値は 2 を掛けて出力stringになります。 EJSON.stringify()はコレクションを更新しません。

ネストされたアドレスを使用してsalesWithAddressコレクションを作成します。

db.salesWithAddress.insertMany( [ { custId: 345, purchaseDate: ISODate("2023-07-04"), quantity: 4, cost: Decimal128("100.60"), address: { number: 100, street: "Main Street", ZIP: 12345 } }, { custId: 346, purchaseDate: ISODate("2023-07-12"), quantity: 3, cost: Decimal128("175.45"), address: { number: 200, street: "East Street", ZIP: 12345 } }] )

次の例では、 replacer関数を使用して住所の郵便番号を55555に変更します。

// Retrieve the salesWithAddress contents as an array and save// in queryResultslet queryResults = db.salesWithAddress.find().toArray() // Define a replacer function to change the ZIP codeslet replacer = function( key, value ) { if (key === 'address') { value.ZIP = 55555; } return value;} // Run EJSON.stringify() to change the ZIP codes in queryResultsEJSON.stringify( queryResults, replacer, 3 )

出力例:

[ { "_id": { "$oid": "65498c6562f443aa1490070f" }, "custId": 345, "purchaseDate": { "$date": "2023-07-04T00:00:00Z" }, "quantity": 4, "cost": { "$numberDecimal": "100.60" }, "address": { "number": 100, "street": "Main Street", "ZIP": 55555 } }, { "_id": { "$oid": "65498c6562f443aa14900710" }, "custId": 346, "purchaseDate": { "$date": "2023-07-12T00:00:00Z" }, "quantity": 3, "cost": { "$numberDecimal": "175.45" }, "address": { "number": 200, "street": "East Street", "ZIP": 55555 } }]

BSONデータ型と対応する数値コードのリストについては、「 BSON types 」を参照してください。

次の例では、 replacer関数を使用して、BSON string を string "This is a string"に置き換えます。

// Retrieve the salesWithAddress contents as an array and save// in queryResultslet queryResults = db.salesWithAddress.find().toArray() // Define a replacer function to replace the stringslet replacer = function( key, value ) { if (typeof value === "string") { return "This is a string"; } return value;} // Run EJSON.stringify() to replace the strings in queryResultsEJSON.stringify( queryResults, replacer, 3 )

出力例:

[ { "_id": { "$oid": "This is a string" }, "custId": 345, "purchaseDate": { "$date": "This is a string" }, "quantity": 4, "cost": { "$numberDecimal": "This is a string" }, "address": { "number": 100, "street": "This is a string", "ZIP": 12345 } }, { "_id": { "$oid": "This is a string" }, "custId": 346, "purchaseDate": { "$date": "This is a string" }, "quantity": 3, "cost": { "$numberDecimal": "This is a string" }, "address": { "number": 200, "street": "This is a string", "ZIP": 12345 } }]

mongosh内のファイルに書き込むには、 fs API を使用します。 fsに渡す string の形式を設定するには、 EJSON.stringify()を使用します。

const sales_2023_07 = db.sales.find( { purchaseDate: { $gte: ISODate( "2023-07-01" ), $lte: ISODate( "2023-07-31" ) } }) fs.writeFileSync( 'sales_2023_07.json', EJSON.stringify( sales_2023_07.toArray(), null, 2 ))

この例では、 salesコレクションで 7 月の売上、 2023をクエリします。

  • sales_2023_07 は MongoDB BSON オブジェクトを保存します。

  • EJSON.stringify() はオブジェクトを JSON string としてフォーマットします。

  • fs.writeFileSync() は、形式が設定された stringsales_2023_07.json mongoshを、 を実行したディレクトリにある ファイルに書込みます。

オペレーティング システム shell からクエリを実行するには、 --evalオプションを使用します。

# Note: This example is formatted to fit on the page. mongosh --quiet \ --eval "db.sales.find().forEach( \ o => print( EJSON.stringify( o ) ) )"

このコマンドは、次のようにドキュメントごとに 1 行の JSON を返します。

  • --quiet はmongosh接続情報を抑制します

  • --eval findメソッドを呼び出す

  • .forEach は、 mongoshに応答を反復処理するように指示する JavaScript メソッドです

  • EJSON.stringify() は各ドキュメントを JSON に変換します

出力は次のとおりです。

{"_id":{"$oid":"64da90c1175f5091debcab26"},"custId":345,"purchaseDate":{"$date":"2023-07-04T00:00:00Z"},"quantity":4,"cost":{"$numberDecimal":"100.60"}}{"_id":{"$oid":"64da90c1175f5091debcab27"},"custId":346,"purchaseDate":{"$date":"2023-07-12T00:00:00Z"},"quantity":3,"cost":{"$numberDecimal":"175.45"}}{"_id":{"$oid":"64da90c1175f5091debcab28"},"custId":486,"purchaseDate":{"$date":"2023-08-01T00:00:00Z"},"quantity":9,"cost":{"$numberDecimal":"200.53"}}

単一行の出力形式は、スクリプトに便利です。 EJSON.stringify()は、人間が判読できる形式を生成することもできます。

# Note: This example is formatted to fit on the page. mongosh --quiet \ --eval "db.sales.find().forEach( \ o => print( EJSON.stringify(o, null, 3 ) ) )"

出力は次のとおりです。

# Note: This is only the first document. { "_id": { "$oid": "64da90c1175f5091debcab26" }, "custId": 345, "purchaseDate": { "$date": "2023-07-04T00:00:00Z" }, "quantity": 4, "cost": { "$numberDecimal": "100.60" }}
  • o は、 .forEach()の反復ごとにEJSON.stringify()が変換する BSON 値です。

  • null は、任意のreplacerのプレースホルダーです。 replacerが存在しない場合、 EJSON.stringify()は定義された値を持つすべてのフィールドを返します。

  • 3 は、 spacer値です。 これは、 EJSON.stringify()に新しいレベルの各レベルを 3 スペースでインデントするように指示します。

出力stringに追加のタイプ情報を含めるには、{ relaxed: false } オプションを追加します。

# Note: This example is formatted to fit on the page. mongosh --quiet \ --eval "db.sales.find().forEach( \ o => print( \ EJSON.stringify( o, null, 3, { relaxed: false } ) \ ) )"

出力は次のとおりです。

# Note: This is only the first document. { "_id": { "$oid": "64da90c1175f5091debcab26" }, "custId": { "$numberInt": "345" }, "purchaseDate": { "$date": { "$numberLong": "1688428800000" } }, "quantity": { "$numberInt": "4" }, "cost": { "$numberDecimal": "100.60" }}

EJSON.stringify() は、 jqのような追加の JSON パーサーの必要性を減らす形式オプションを提供します。

# Note: This example is formatted to fit on the page. mongosh --quiet \ --eval "EJSON.stringify( \ db.sales.find( {}, \ { _id: 0, custId: 1, quantity: 1 } ).toArray(), null, 2 \ );"

出力は次のとおりです。

[ { "custId": 345, "quantity": 4 }, { "custId": 346, "quantity": 3 }, { "custId": 486, "quantity": 9 }]

mongosh shell は、レガシーのmongo shell とは異なる出力を返します。 レガシーのmongo shell と同様の方法で出力をフォーマットする必要があるスクリプトがある場合は、 EJSON.stringify()を使用してmongosh出力を再フォーマットしてみてください。

mongoshとmongoでサンプル クエリを実行すると、さまざまな形式が表示されます。

db.sales.find( { custId: 345 } )

レガシー出力:

{ "_id" : ObjectId("64da90c1175f5091debcab26"), "custId" : 345, "purchaseDate" : ISODate("2023-07-04T00:00:00Z"), "quantity" : 4, "cost" : NumberDecimal("100.60") }

mongosh output:

db.sales.find( { custId: 345 } )[ { _id: ObjectId("64da90c1175f5091debcab26"), custId: 345, purchaseDate: ISODate("2023-07-04T00:00:00.000Z"), quantity: 4, cost: Decimal128("100.60") }]

EJSON.stringify()を使用して出力を再フォーマットします。

EJSON.stringify( db.sales.find( { custId: 345 } ).toArray() )
[{"_id":{"$oid":"64da90c1175f5091debcab26"},"custId":345,"purchaseDate":{"$date":"2023-07-04T00:00:00Z"},"quantity":4,"cost":{"$numberDecimal":"100.60"}}]