Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Go Driver
/

ドキュメントのデータ形式: 拡張 JSON

JSON は、オブジェクト、配列、数値、string、ブール値、null の値を表すデータ形式です。拡張JSON形式では、 $MongoDB がデータを保存するために使用する形式であるBSONの各型に直接対応するフィールド型情報を表すために、 文字がプレフィックスが付いたキーの予約セットが定義されます。

MongoDB拡張JSON は、 BSONデータを表すためのさまざまな string 形式を機能します。各形式は JSON RFC に準拠し、特定のユースケースを満たしています。

拡張形式(標準形式とも呼ばれます)は、情報を失うことなく双方向変換を行うために、すべてのBSON型に対して特定の表現を備えています。緩和形式は、より簡潔で通常のJSONに近いものですが、数値フィールドの特定のバイトサイズなど、すべての型情報を表すものではありません。

次の表は、 JSON形式の説明を示しています。

名前
説明

拡張

Also known as the canonical format, this JSON representation avoids loss of BSON type information.
This format prioritizes type preservation at the loss of human-readability and interoperability with older formats.

緩和モード

JSON representation that describes BSON documents with some type information loss.
This format prioritizes human-readability and interoperability at the loss of certain type information.

Shell

JSON representation that matches the syntax used in the MongoDB shell.
This format prioritizes compatibility with the MongoDB shell, which often uses JavaScript functions to represent types.

厳密

Deprecated This representation is the legacy format that fully conforms to the JSON RFC and allows any JSON parser to read the type information.

JSON、 BSON、 拡張JSONの詳細については、 MongoDB ServerマニュアルのJSONとBSON、および 拡張JSON参照に関する記事を参照してください。

次のタブには、それぞれの 拡張JSON形式で表される ObjectId、date、long 数フィールドを含むドキュメントが表示されます。[] タブから [] を選択すると、各JSON形式で表示される同じデータを確認できます。

{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": { "$numberLong": "1601499609" }},
"numViews": { "$numberLong": "36520312" }
}
{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": "2020-09-30T18:22:51.648Z" },
"numViews": 36520312
}
{
"_id": ObjectId("573a1391f29313caabcd9637"),
"createdAt": ISODate("2020-09-30T18:22:51.648Z"),
"numViews": NumberLong("36520312")
}
{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": 1601499609 },
"numViews": { "$numberLong": "36520312" }
}

bson.UnmarshalExtJSON() メソッドを呼び出すと、拡張JSON string を 構造体に読み込むことができます。このメソッドは、拡張JSON string を解析し、その結果を指定された値パラメーターに保存します。

この例では、拡張JSON string を次の Person 構造体に読み込む方法を示しています。

type Person struct {
ID bson.ObjectID `bson:"_id"`
Name string
Age int
Birthday bson.DateTime
Address Address
Hobbies []string
}
type Address struct {
Street string
City string
State string
}

次のコードでは、UnmarshalExtJSON() メソッドを使用して拡張JSON string を読み取り、データを Person のインスタンスにアンマーシャリングします。

var extJsonString = "{\"_id\":{\"$oid\":\"578f6fa2df35c7fbdbaed8c5\"},\"name\":\"Liana Ruiz\",\"age\":46,\"birthday\":{\"$date\":\"1988-01-15T00:00:00Z\"},\"address\":{\"street\":\"500 Slippery Rock Road\",\"city\":\"Round Rock\",\"state\":\"AR\"},\"hobbies\":[\"cycling\", \"baking\"]}"
var p Person
err := bson.UnmarshalExtJSON([]byte(extJsonString), false, &p)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Go Struct Representation:\n%+v\n", p)
Go Struct Representation:
{ID:ObjectID("578f6fa2df35c7fbdbaed8c5") Name:Liana Ruiz Age:46 Birthday:569203200000 Address:{Street:500 Slippery Rock Road City:Round Rock State:AR} Hobbies:[cycling baking]}

bson.MarshalExtJSON() メソッドを呼び出すと、 構造体またはBSONドキュメントのインスタンスから拡張JSON string を生成できます。次の例では、 構造体またはBSONドキュメント のいずれかから、緩和形式の拡張JSON string を作成します。対応する例を表示するには、Struct タブまたは bson.Dタブを選択します。

var person = Person{
ID: bson.NewObjectID(),
Name: "Matteo Carisi",
Age: 49,
Birthday: bson.NewDateTimeFromTime(time.Date(1975, 10, 30, 0, 0, 0, 0, time.UTC)),
Address: Address{Street: "14a Corner Court", City: "Springfield", State: "IL"},
Hobbies: []string{"cooking", "birdwatching"},
}
newExtJsonStringFromStruct, err := bson.MarshalExtJSON(person, false, true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Extended JSON Representation:\n%s\n", newExtJsonStringFromStruct)
Extended JSON Representation:
{"_id":{"$oid":"686688fa7c1a2e75405f4697"},"name":"Matteo Carisi","age":49,"birthday":{"$date":"1975-10-30T00:00:00Z"},"address":{"street":"14a Corner Court","city":"Springfield","state":"IL"},"hobbies":["cooking","birdwatching"]}
bsonDocument := bson.D{{"hello", "world"}, {"number", 1}}
newExtJsonStringFromBson, err := bson.MarshalExtJSON(bsonDocument, false, true)
if err != nil {
panic(err)
}
fmt.Printf("Extended JSON Representation:\n%s\n", newExtJsonStringFromBson)
Extended JSON Representation:
{"hello":"world","number":1}

MarshalExtJSON() に対する 2 番目のパラメータによって、出力文字列が 標準(拡張)形式になるか、 緩和形式になるかが決まります。 上記の例では falsecanonical パラメーターとして渡しているため、出力は Relaxed JSONとなります。

注意

エポック時間より前の日付

1 月 1、1970、00:00:00 UTC(エポック時間)より前の日付値をマーシャリングすると、 Relaxed JSONに Unix タイムスタンプとして表示されます。日付が UNIXエポック時間より後の場合は、読み取り可能な日付形式に表示されます。

bson.MarshalExtJSONIndent() メソッドを使用して、改行、接頭辞、インデントを含む形式の拡張JSON string を出力できます。

次のコードでは、MarshalExtJSONIndent() メソッドを使用して、2 つのスペースのインデントで形式設定された前述の例のJSON string を出力します。

formattedString, err := bson.MarshalExtJSONIndent(person, false, true, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", formattedString)
{
"_id": {
"$oid": "686688fa7c1a2e75405f4697"
},
"name": "Matteo Carisi",
"age": 49,
"birthday": {
"$date": "1975-10-30T00:00:00Z"
},
"address": {
"street": "14a Corner Court",
"city": "Springfield",
"state": "IL"
},
"hobbies": [
"cooking",
"birdwatching"
]
}

このガイドで使用されているメソッドとタイプの詳細については、次の API ドキュメントを参照してください。

戻る

BSON

項目一覧