nickzuck_007

Using change streams #2

Jun 20th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 2.00 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "context"
  5.     "fmt"
  6.     "go.mongodb.org/mongo-driver/mongo"
  7.     "go.mongodb.org/mongo-driver/mongo/options"
  8.     "go.mongodb.org/mongo-driver/mongo/readpref"
  9.     "github.com/globalsign/mgo/bson"
  10.     "time"
  11. )
  12.  
  13. type InsertChangeStream struct{
  14.     OperationType string `json:"operationType"`
  15.     Document interface{} `json:"fullDocument"`
  16.     DocumentKey DocumentKeyStruct `json:"documentKey"`
  17. }
  18.  
  19. type DocumentKeyStruct struct{
  20.     Id map[string]string `json:"_id"`
  21. }
  22.  
  23. // TODO: Get below structs from models
  24. // TODO: Add es tags
  25. type DemoDocument struct {
  26.     A string `bson:"a" json:"a"`
  27.     B string `bson:"b" json:"b"`
  28. }
  29.  
  30. func main() {
  31.     mongoDBURI := "mongodb://localhost:27017"
  32.     client, err := mongo.NewClient(options.Client().ApplyURI(mongoDBURI))
  33.     ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
  34.  
  35.     _ = client
  36.     _ = ctx
  37.     _ = err
  38.     err = client.Connect(ctx)
  39.     if err != nil {
  40.         fmt.Println("Err while context.WithTimeout : ", err.Error())
  41.     }
  42.  
  43.     err = client.Ping(ctx, readpref.Primary())
  44.     if err != nil {
  45.         fmt.Println("error while ping : ", err.Error())
  46.     }
  47.     fmt.Println("connection established")
  48.     db := client.Database("testdb")
  49.     coll := db.Collection("collection2")
  50.  
  51.     cs, err := coll.Watch(ctx, mongo.Pipeline{})
  52.     defer cs.Close(ctx)
  53.  
  54.     if err != nil {
  55.         fmt.Println("Err while watching collection : ", err.Error())
  56.     }
  57.  
  58.  
  59.     ok := cs.Next(ctx)
  60.     fmt.Println(" ok fasdf", ok )
  61.     for ok {
  62.         next := cs.Current
  63.         //fmt.Println(ok, next)
  64.         fmt.Println(next.String())
  65.         var insertData interface{}
  66.         //err = json.Unmarshal([]byte(next.String()), &insertData)
  67.         //if err != nil {
  68.         //  fmt.Println("Error while json marshalling: ", err.Error())
  69.         //}
  70.         cs.Decode(insertData)
  71.         fmt.Println("insert data", insertData)
  72.         ok = cs.Next(ctx)
  73.         //document := insertData.Document
  74.         //objectId := insertData.DocumentKey.Id["$oid"]
  75.  
  76.  
  77.     }
  78.  
  79.     //for cs.Next(ctx) {
  80.     //  //elem := bson.NewDocument()
  81.     //  if err := cs.Decode(elem); err != nil {
  82.     //      log.Fatal(err)
  83.     //  }
  84.     //
  85.     //}
  86.  
  87.  
  88. }
Add Comment
Please, Sign In to add comment