JSON to BSON
Generate MongoDB BSON code from JSON — Go (bson.D / bson.M), Node.js, and Python (pymongo).
What is BSON?
BSON (Binary JSON) is the binary-encoded serialization format MongoDB uses internally to store documents and transmit data over the network. While JSON is text-based, BSON is binary — it is more efficient to parse, supports additional data types (like native dates, 64-bit integers, ObjectId, and binary data) that JSON does not have, and is the native document format MongoDB drivers work with.
When writing MongoDB queries and insert operations in Go, Node.js, or Python, you express JSON-like data using BSON types from the driver library. In Go, that means bson.D (ordered document) or bson.M (unordered map). This tool converts any JSON object to ready-to-use BSON driver code in your chosen language.
bson.D vs bson.M in Go
| Type | Order preserved? | Use case | Query filter? | Performance |
|---|---|---|---|---|
| bson.D | Yes | Insert documents, ordered pipelines | Yes (required for $sort) | Slightly slower |
| bson.M | No | Simple queries and filters | Yes (for most cases) | Slightly faster |
| struct + bson tags | Yes | Typed application models | Yes | Fastest (type-safe) |
Prefer structs with bson tags for application models. Use bson.D for aggregation pipelines where key order matters (e.g., $sort). Use bson.M for simple ad-hoc queries.
Go Struct with bson Tags (Recommended)
type User struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id"`
Name string `bson:"name" json:"name"`
Email string `bson:"email" json:"email"`
Age int64 `bson:"age" json:"age"`
Active bool `bson:"active" json:"active"`
Created time.Time `bson:"created_at" json:"created_at"`
}
// Insert
user := User{Name: "Ravi", Email: "ravi@example.com", Age: 28, Active: true}
result, err := coll.InsertOne(ctx, user)
// Find
var found User
err = coll.FindOne(ctx, bson.M{"email": "ravi@example.com"}).Decode(&found)Common Use Cases
- ▸Prototype insertion — Quickly generate code to insert a sample JSON document into MongoDB without manually writing bson.D or bson.M.
- ▸Query filters — Build a filter document from a JSON object to use in FindOne or Find queries.
- ▸Language migration — Migrating from Node.js to Go? See how the same document structure looks in Go's BSON library.
- ▸Learning MongoDB drivers — Compare how the same MongoDB operation looks across Go, Node.js, and Python side-by-side.