Docs Menu

Docs HomeGo

Watch for Changes

You can open a change stream on a MongoCollection, MongoDatabase, or MongoClient by using the Watch() method.

Tip

Read the Usage Examples to learn how to run this example.

The following example opens a change stream on the haikus collection and prints inserted documents:

coll := client.Database("insertDB").Collection("haikus")
pipeline := mongo.Pipeline{bson.D{{"$match", bson.D{{"operationType", "insert"}}}}}
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!")
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.

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": ...,
"title": "Record of a Shriveled Datum",
"text": "No bytes, no problem. Inserting a document. In MongoDB"
}

Important

Make sure to shut down this usage example once you finish by closing your terminal.

To learn more about opening a change stream and handling potential errors, see:

Watch()

←  Perform Bulk OperationsCount Documents →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.