GoLang 中用 MongoDB Watch 监听指定字段的变化

需要 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 ,都变化,用$and。注意 bson.A 里面是 bson.D

坑:如果使用 Robo 3T 进行修改,operationType是 replace。

原文地址:https://www.cnblogs.com/flipped/p/mongo-watch-specified-fields.html