Monitor Data Changes
You can open a change stream on a Collection
,
Database
, or Client
by using the Watch()
method.
Example
Tip
Read the Usage Examples to learn how to run this example.
The following example opens a change stream on the restaurants
collection
and prints inserted documents:
coll := client.Database("sample_restaurants").Collection("restaurants") // Creates instructions to watch for insert operations pipeline := mongo.Pipeline{bson.D{{"$match", bson.D{{"operationType", "insert"}}}}} // Creates a change stream that receives change events cs, err := coll.Watch(context.TODO(), pipeline) if err != nil { panic(err) } defer cs.Close(context.TODO()) fmt.Println("Waiting For Change Events. Insert something in MongoDB!") // Prints a message each time the change stream receives an event for cs.Next(context.TODO()) { var event bson.M if err := cs.Decode(&event); err != nil { panic(err) } output, err := json.MarshalIndent(event["fullDocument"], "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", output) } if err := cs.Err(); err != nil { panic(err) }
View a fully runnable example.
Expected Result
After you run the full example, run the Insert a Document usage example in a different shell. Once you run the insert operation, you should see the following output:
// results truncated { "_id": ..., "name": "8282", "cuisine": "Korean" }
Important
Make sure to shut down this usage example once you finish by closing your terminal.
Additional Information
To learn more about opening a change stream and handling potential errors, see:
Fundamentals page on change streams
MongoDB Server Manual Change Streams Documentation