-
-
Save prestonvasquez/30f15e9f84c76a63e6bf818663a18309 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"sync" | |
"time" | |
"go.mongodb.org/mongo-driver/bson" | |
"go.mongodb.org/mongo-driver/mongo" | |
"go.mongodb.org/mongo-driver/mongo/options" | |
) | |
func main() { | |
ctx := context.Background() | |
opts := options.Client().ApplyURI("mongodb://localhost:27017") | |
client, err := mongo.Connect(ctx, opts) | |
if err != nil { | |
panic(err) | |
} | |
collection := client.Database("test").Collection("coll") | |
pipeline := mongo.Pipeline{bson.D{{ | |
Key: "$match", | |
Value: bson.D{ | |
{Key: "fullDocument.env", Value: "x"}, | |
{Key: "fullDocument.requestUUID", Value: "y"}, | |
}}, | |
}} | |
option := options.ChangeStream().SetFullDocument(options.UpdateLookup).SetMaxAwaitTime(5 * time.Second) | |
changeStream, err := collection.Watch(ctx, pipeline, option) | |
if err != nil { | |
panic(err) | |
} | |
defer func() { | |
if err := changeStream.Close(ctx); err != nil { | |
panic(err) | |
} | |
}() | |
doc := bson.D{{Key: "num", Value: 1}} | |
_, err = collection.InsertOne(ctx, doc) | |
if err != nil { | |
panic(err) | |
} | |
wg := sync.WaitGroup{} | |
wg.Add(2) | |
go func() { | |
defer wg.Done() | |
for changeStream.Next(context.Background()) { | |
} | |
}() | |
// Can't do this: | |
go func() { | |
defer wg.Done() | |
changeStream.Close(ctx) | |
}() | |
// Must do this: | |
//defer changeStream.Close(ctx) | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I want to break watch loop at any time. Please review my codes.