This chapter introduces how Golang expresses the JSON data structure of MongoDB. As we all know, MongoDB data and query conditions are described using JSON structures. So, how can we express such JSON structures in Go language?

bson package

The official Go language driver provided by MongoDB offers a bson package, which includes several data structures for describing JSON data.

bson package: go.mongodb.org/mongo-driver/bson

Key-Value Arrays

The bson.D type is used to describe ordered key-value arrays, which are commonly used to express MongoDB query expressions and JSON data.

Definition:

// Key-Value array
type D [] E

// Key-Value structure
type E struct {
	Key   string
	Value interface{}
}

Example of a query expression:

bson.D{{"qty", bson.D{{"$lt", 30}}}}

Equivalent expression:

{"qty": {"$lt": 30} }

Example of document data:

bson.D{
	{"item", "journal"},
	{"qty", 25},
	{"size", bson.D{
		{"h", 14},
		{"w", 21},
		{"uom", "cm"},
	}},
	{"status", "A"},
}

Equivalent JSON:

{
	"item": "journal",
	"qty": 25,
	"size": {
		"h": 14,
		"w": 21,
		"uom": "cm"
	},
	"status": "A"
}

JSON Arrays

The bson.A is used to define JSON arrays.

Definition of JSON arrays:

type A []interface{}

Example 1:

bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}}

Equivalent JSON:

["bar", "world", 3.14159, {"qux": 12345}]

Example 2:

bson.A{"A", "D"}

Equivalent JSON:

["A", "D"]

Map Key-Value Structure

The bson.M is used to describe unordered key-value pairs, unlike bson.D, which cares about the storage order of keys.

Definition:

type M map[string]interface{}

Example:

bson.M{"foo": "bar", "hello": "world", "pi": 3.14159}

Equivalent JSON:

{
	"foo": "bar",
	"hello": "world",
	"pi": 3.14159
}