Skip to content

Instantly share code, notes, and snippets.

@serkanserttop
Created September 8, 2014 17:58
Show Gist options
  • Save serkanserttop/2b89fe2992d633c81cf4 to your computer and use it in GitHub Desktop.
Save serkanserttop/2b89fe2992d633c81cf4 to your computer and use it in GitHub Desktop.
Insert the original.json file into a running MongoDB instance. I am using localhost:27017 for this example. That document is fetched and re-inserted after its _id is changed. I was hoping it would preserve fields with null values but it does not.
{
"_id" : "456321",
"user" : {
"id" : 654321
}
}
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"log"
"os"
"sync"
"time"
)
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
type User struct {
Id *int `json:"id" bson:"id"`
NestedIntNull *int `json:"nested_int_null,omitempty" bson:"nested_int_null,omitempty"`
NestedBoolNull *bool `json:"nested_bool_null,omitempty" bson:"nested_bool_null,omitempty"`
NestedStrNull *string `json:"nested_str_null,omitempty" bson:"nested_str_null,omitempty"`
}
type Tweet struct {
Id string `json:"_id" bson:"_id"`
IntNull *int `json:"int_null,omitempty" bson:"int_null,omitempty"`
BoolNull *bool `json:"bool_null,omitempty" bson:"bool_null,omitempty"`
StrNull *string `json:"str_null,omitempty" bson:"str_null,omitempty"`
User *User `json:"user" bson:"user"`
}
const (
MongoDBHosts = "localhost:27017"
AuthDatabase = "tweets"
TestDatabase = "tweets"
ConcurrentNumberOfQueries = 1
)
func run() error {
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{MongoDBHosts},
Timeout: 60 * time.Second,
Database: AuthDatabase,
}
mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
log.Fatalf("CreateSession: %s\n", err)
}
mongoSession.SetMode(mgo.Monotonic, true)
var waitGroup sync.WaitGroup
waitGroup.Add(ConcurrentNumberOfQueries)
for query := 0; query < ConcurrentNumberOfQueries; query++ {
go RunQuery(query, &waitGroup, mongoSession)
}
waitGroup.Wait()
log.Println("All Queries Completed")
return nil
}
func RunQuery(query int, waitGroup *sync.WaitGroup, mongoSession *mgo.Session) {
defer waitGroup.Done()
sessionCopy := mongoSession.Copy()
defer sessionCopy.Close()
collection := sessionCopy.DB(TestDatabase).C("tweets")
log.Printf("RunQuery : %d : Executing\n", query)
var tweet Tweet
err := collection.FindId("123456").One(&tweet) //original.json
if err != nil {
log.Printf("RunQuery : ERROR : %s\n", err)
return
}
tweet.Id = "456321"
err = collection.Insert(&tweet) //inserted.json
if err != nil {
log.Fatal(err)
}
}
{
"_id" : "123456",
"int_null" : null,
"bool_null" : null,
"str_null" : null,
"user" : {
"id" : 654321,
"nested_int_null" : null,
"nested_bool_null" : null,
"nested_str_null" : null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment