Skip to content

Instantly share code, notes, and snippets.

@tfogo
Created September 30, 2019 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfogo/fea1a80c565f7e97f7464c6b0c39640f to your computer and use it in GitHub Desktop.
Save tfogo/fea1a80c565f7e97f7464c6b0c39640f to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"log"
"strings"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Generates a document of the form {_id: X, key: Y} where the total
// document size is equal to 16 MiB. Generates a long string for Y in
// order to reach 16 MiB.
func generate16MiBDocument() bson.M {
// Here's a breakdown of bytes in the document:
//
// 4 bytes = document length
// 1 byte = element type (ObjectID = \x07)
// 4 bytes = key name ("_id" + \x00)
// 12 bytes = ObjectID value
// 1 byte = element type (string = \x02)
// 4 bytes = key name ("key" + \x00)
// 4 bytes = string length
// X bytes = string of length X bytes
// 1 byte = \x00
// 1 byte = \x00
//
// Therefore the string length should be: 1024*1024*16 - 32
// Note, _id is added on the server
var b strings.Builder
size := 1024*1024*16 - 32
b.Grow(size)
for i := 0; i < size; i++ {
b.WriteByte(byte('A'))
}
return bson.M{"key": b.String()}
}
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017/test")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
largeDoc := generate16MiBDocument()
_, err = client.Database("foo").Collection("bar").InsertOne(context.Background(), largeDoc)
if err != nil {
fmt.Printf("ERROR: %v\n\n", err)
} else {
fmt.Print("Successfully inserted document")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment