需要 MongoDB 3.6 及以上, 需要 ReplicaSet 模式。
监听一个字段的变化:
func watch(coll *mongo.Collection) {
match := bson.D{{"operationType", "update"},
{"updateDescription.updatedFields.name", bson.D{{"$exists", true}}}}
coll.Watch(context.Background(), mongo.Pipeline{{{"$match", match}}},
options.ChangeStream().SetFullDocument(options.UpdateLookup))
}
监听两个字段的变化:
func watch(coll *mongo.Collection) {
match := bson.D{
{"operationType", "update"},
{"$or", bson.A{
bson.D{{"updateDescription.updatedFields.name",
bson.D{{"$exists", true}},
}},
bson.D{{"updateDescription.updatedFields.age",
bson.D{{"$exists", true}},
}},
}}
coll.Watch(context.Background(), mongo.Pipeline{{{"$match", match}}},
options.ChangeStream().SetFullDocument(options.UpdateLookup))
}
$or$andbson.Abson.D