定義
$serializeEJSONバージョン8.3の新機能。
BSON値を 拡張JSON (EJSON)形式に変換します。結果は EJSON 型のラッパーを含むBSONドキュメントで、 を使用してJSON string
$toStringに変換できます。
構文
{ $serializeEJSON: { input: <expression>, relaxed: <boolean>, onError: <expression> } }
$serializeEJSON 次のフィールドが含まれるドキュメントについて、
フィールド | タイプ | 必要性 | 説明 |
|---|---|---|---|
| 式 | 必須 | 拡張JSON形式に変換するBSON値。 |
| ブール値 | 任意 | 緩和型拡張JSON形式を使用するかどうかを指定します。
デフォルト: |
| 式 | 任意 | 変換中に操作でエラーが発生した場合に返される値。 指定されていない場合、エラーが発生すると、操作はエラーをスローして停止します。 |
動作
標準形式と緩和形式の比較
次の表は、一般的なBSON型が 拡張JSONに変換される方法を示しています。
BSON 型 | 標準型拡張 JSON | 緩和型拡張 JSON |
|---|---|---|
Int32 |
|
|
Int64 |
|
|
Double |
|
|
ObjectId |
| 標準と同じ |
日付 |
|
|
バイナリ |
| 標準と同じ |
正規表現 |
| 標準と同じ |
NULL および欠損値
input 値が null または欠落している場合、$serializeEJSON は null を返します。
例
このページの例では、sample_mflixサンプルデータセットのデータを使用します。このデータセットを自己管理型MongoDB配置にロードする方法の詳細については、サンプルデータセットをロードするを参照してください。サンプルデータベースに変更を加えた場合、このページの例を実行するには、データベースを削除して再作成する必要がある場合があります。
標準型拡張JSON の例
次の例では、映画ドキュメントを標準型拡張JSON形式に変換します。
db.movies.aggregate([ { $match: { title: "Inception" } }, { $project: { ejson: { $serializeEJSON: { input: "$$ROOT" } } } } ])
{ _id: ObjectId("573a1398f29313caabcea974"), ejson: { _id: { $oid: "573a1398f29313caabcea974" }, title: "Inception", year: { $numberInt: "2010" }, runtime: { $numberInt: "148" }, released: { $date: { $numberLong: "1279238400000" } }, cast: [ "Leonardo DiCaprio", "Joseph Gordon-Levitt", "Ellen Page", "Tom Hardy" ], genres: [ "Action", "Sci-Fi", "Thriller" ], directors: [ "Christopher Nolan" ] } }
緩和型拡張JSON の例
次の例では、より読みやすい出力を得るために relaxed オプションを使用しています。
db.movies.aggregate([ { $match: { title: "Inception" } }, { $project: { ejson: { $serializeEJSON: { input: "$$ROOT", relaxed: true } } } } ])
{ _id: ObjectId("573a1398f29313caabcea974"), ejson: { _id: { $oid: "573a1398f29313caabcea974" }, title: "Inception", year: 2010, runtime: 148, released: { $date: "2010-07-16T00:00:00.000Z" }, cast: [ "Leonardo DiCaprio", "Joseph Gordon-Levitt", "Ellen Page", "Tom Hardy" ], genres: [ "Action", "Sci-Fi", "Thriller" ], directors: [ "Christopher Nolan" ] } }
JSON string への変換
EJSON 結果をJSON string に変換するには、$serializeEJSON $toStringと を組み合わせます。
db.movies.aggregate([ { $match: { title: "The Godfather" } }, { $project: { title: 1, jsonString: { $toString: { $serializeEJSON: { input: "$$ROOT" } } } } } ])
[ { _id: '573a13c5f29313caabd6ee62', title: 'The Godfather', jsonString: `{"_id":"573a13c5f29313caabd6ee62",` + `"fullplot":"When the aging head of a famous crime family decides to transfer his position to one of his subalterns, a series of unfortunate events start happening to the family, and a war begins between all the well-known families leading to insolence, deportation, murder and revenge, and ends with the favorable successor being finally chosen.",` + `"imdb":{"rating":9.2,"votes":1038358,"id":68646},` + `"year":1972,` + `"plot":"The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",` + `"genres":["Crime","Drama"],` + `"rated":"R",` + `"metacritic":100,` + `"title":"The Godfather",` + `"lastupdated":"2015-09-02 00:08:23.680000000",` + `"languages":["English","Italian","Latin"],` + `"writers":["Mario Puzo (screenplay)","Francis Ford Coppola (screenplay)","Mario Puzo (novel)"],` + `"type":"movie",` + `"tomatoes":{"website":"http://www.thegodfather.com","viewer":{"rating":4.4,"numReviews":725773,"meter":98},"dvd":{"$date":"2001-10-09T00:00:00.000Z"},"critic":{"rating":9.2,"numReviews":84,"meter":99},"lastUpdated":{"$date":"2015-09-12T17:15:13.000Z"},"consensus":"One of Hollywood's greatest critical and commercial successes, The Godfather gets everything right; not only did the movie transcend expectations, it established new benchmarks for American cinema.","rotten":1,"production":"Paramount Pictures","fresh":83},` + `"poster":"https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SY1000_SX677_AL_.jpg",` + `"num_mflix_comments":131,` + `"released":{"$date":"1972-03-24T00:00:00.000Z"},` + `"awards":{"wins":33,"nominations":19,"text":"Won 3 Oscars. Another 30 wins & 19 nominations."},` + `"countries":["USA"],` + `"cast":["Marlon Brando","Al Pacino","James Caan","Richard S. Castellano"],` + `"directors":["Francis Ford Coppola"],` + `"runtime":175}` } ]
注意
前の例の jsonStringフィールドは、読みやすいように再フォーマットされています。実際の出力では、 JSON string は空白のない単一行です。
特定のフィールドを直列化
ドキュメント全体ではなく、特定のフィールドをシリアル化できます。
db.movies.aggregate([ { $match: { year: { $gte: 2010 } } }, { $project: { title: 1, metadataEJSON: { $serializeEJSON: { input: { releaseDate: "$released", runtime: "$runtime", imdbRating: "$imdb.rating" } } } } } ])
[ { _id: '573a13c5f29313caabd6ee61', title: 'Inception', metadataEJSON: { releaseDate: { '$date': '2010-07-16T00:00:00.000Z' }, runtime: 148, imdbRating: 8.8 } } ]
エラー処理での onError の使用
次の例では、直列化が失敗した場合にフォールバック値を提供するために onError を使用します。
db.movies.aggregate([ { $project: { title: 1, ejson: { $serializeEJSON: { input: "$customField", onError: { error: "Serialization failed" } } } } } ])
詳細
MongoDB Shell には、 拡張JSONを操作するのに役立つ組み込みメソッドが用意されています。詳しくは、「 EJSON 」を参照してください。