Skip to content

Instantly share code, notes, and snippets.

@mmcclimon
Last active June 2, 2025 17:23
Show Gist options
  • Select an option

  • Save mmcclimon/29ea8f89ea01826e80f3fd1db2856d30 to your computer and use it in GitHub Desktop.

Select an option

Save mmcclimon/29ea8f89ea01826e80f3fd1db2856d30 to your computer and use it in GitHub Desktop.
Mongo go driver v1/v2
package main
import (
"bytes"
"fmt"
"log"
"github.com/sanity-io/litter"
bson1 "go.mongodb.org/mongo-driver/bson"
bson2 "go.mongodb.org/mongo-driver/v2/bson"
)
func main() {
doc := bson1.D{
{"_id", 17},
{"d1", bson1.D{
{"foo", "bar"},
{"baz", "quux"},
}},
{"d2", bson1.D{
{"nested", bson1.D{
{"a", 1},
}},
}},
}
raw, err := bson1.Marshal(doc)
if err != nil {
log.Fatal(err)
}
doV1(raw)
doV2(raw, false)
doV2(raw, true)
}
func doV1(raw []byte) {
fmt.Println("Go Driver V1")
fmt.Println("------------")
var m map[string]any
err := bson1.Unmarshal(raw, &m)
if err != nil {
log.Fatal(err)
}
litter.Dump(m)
}
func doV2(raw []byte, decodeToM bool) {
fmt.Printf("\nGo Driver V2 (defaultDocumentM=%v)\n", decodeToM)
fmt.Println("---------------------------------")
decoder := bson2.NewDecoder(bson2.NewDocumentReader(bytes.NewReader(raw)))
if decodeToM {
decoder.DefaultDocumentM()
}
var m map[string]any
err := decoder.Decode(&m)
if err != nil {
log.Fatal(err)
}
litter.Dump(m)
}
Go Driver V1
------------
map[string]interface {}{
"_id": 17,
"d1": map[string]interface {}{
"baz": "quux",
"foo": "bar",
},
"d2": map[string]interface {}{
"nested": map[string]interface {}{
"a": 1,
},
},
}
Go Driver V2 (defaultDocumentM=false)
---------------------------------
map[string]interface {}{
"_id": 17,
"d1": bson.D{
bson.E{
Key: "foo",
Value: "bar",
},
bson.E{
Key: "baz",
Value: "quux",
},
},
"d2": bson.D{
bson.E{
Key: "nested",
Value: bson.D{
bson.E{
Key: "a",
Value: 1,
},
},
},
},
}
Go Driver V2 (defaultDocumentM=true)
---------------------------------
map[string]interface {}{
"_id": 17,
"d1": bson.M{
"baz": "quux",
"foo": "bar",
},
"d2": bson.M{
"nested": bson.M{
"a": 1,
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment