JSON to Go Bson Transformer — Numio
Rewrites a JSON document as a Go literal built from bson.M (objects) and bson.A (arrays) for the MongoDB Go driver, with the trailing commas Go requires. Keys keep their order, null becomes nil and strings are copied unchanged.
Porting a MongoDB query or filter tested in mongosh or Compass into Go code.
JSON
Go Bson
When to use it
- Porting a MongoDB query or filter tested in mongosh or Compass into Go code.
- Writing an aggregation stage or update document as an inline Go literal in a test.
How to use
- Paste the query, filter or document as strict JSON (quoted keys, no ObjectId(...) or ISODate(...) shell helpers).
- Copy the bson.M{...} literal from the Go panel; operators such as $gte, $in and $or are kept as string keys.
- Import go.mongodb.org/mongo-driver/bson and pass the value to Find, UpdateOne or Aggregate, editing types as noted below.
JSON input
{
"status": "active",
"deletedAt": null,
"age": { "$gte": 18 },
"tags": { "$in": ["go", "mongo"] },
"$or": [
{ "verified": true },
{ "score": { "$gt": 90 } }
]
}Go bson.M / bson.A
bson.M{
"status": "active",
"deletedAt": nil,
"age": bson.M{
"$gte": 18,
},
"tags": bson.M{
"$in": bson.A{
"go",
"mongo",
},
},
"$or": bson.A{
bson.M{
"verified": true,
},
bson.M{
"score": bson.M{
"$gt": 90,
},
},
},
}Details and limitations
The JSON is parsed and walked in your browser to build the literal; nothing is sent to a server.
null becomes nil. Numbers are untyped Go constants, so 18 becomes int and 1.5 float64; integers beyond 2^53 lose precision when the JSON is parsed.
Strings are written as Go string literals, so brackets or braces inside them, such as "tags[0]", are left untouched.
It outputs bson.M, which is unordered. Use bson.D where field order matters, such as sort documents or some pipeline stages.
FAQ
Can I paste a mongosh query with ObjectId() or ISODate()?
No. The input must be valid JSON, so shell helpers cause a parse error. Use plain strings, then replace them in Go with an ObjectID from hex (primitive.ObjectIDFromHex in driver v1) or a time.Time value.
Does it generate Go structs?
No, it produces map and slice literals only. For typed structs with json tags use the JSON to Go page.
Does the root have to be an object?
No. A root array becomes bson.A{...}, which suits an aggregation pipeline, where each stage is a bson.M.