C# - 使用 $match 更改 MongoDB 中的流

C# - Change Streams in MongoDB with $match

我正在尝试将 MongoDB 中的更改流缩小到与文档的 _id 匹配的特定文档,因为我在一个集合中有很多文档。任何人都知道如何在 C# 中执行此操作?这是我尝试过但无济于事的最新消息:

{
    var userID = "someIdHere";
    var match = new BsonDocument
    {
        {
            "$match",
            new BsonDocument
            {
                {"_id", userID}
            }
        }
    };
    var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<Class>>().Match(match);

    var options = new ChangeStreamOptions { FullDocument = ChangeStreamFullDocumentOption.UpdateLookup };
    var cursor = collection.Watch(pipeline, options).ToEnumerable();
    foreach (var change in cursor)
    {
        Debug.WriteLine(change.FullDocument.ToJson());
        Debug.WriteLine(change.ResumeToken + " " + change.OperationType);
    }
} 

如果我将光标更改为您在下面看到的内容,它会起作用,但它 returns 世界和 returns 当存在 activity 中的任何 _id 时更改流文件。这不是我想要的。

var cursor = collection.Watch().ToEnumerable();

在四处搜索之后,我能够将我在网上找到的其他问题的零碎信息拼凑起来,并得出以下解决方案。它就像一个魅力!

我不仅能够过滤 Change Stream 以便它只识别更新,而且我能够将流缩小到特定文档 _id 并使其更加精细地找到对名为 LastLogin 的字段的特定更改那个_id。这是我想要的,因为默认更改流返回集合上发生的任何更新。

我希望这对遇到与我相同问题的人有所帮助。干杯。

{
    var db = client.GetDatabase(dbName);
    var collectionDoc = db.GetCollection<BsonDocument>(collectionName);
    var id = "someID";

    //Get the whole document instead of just the changed portion
    var options = new ChangeStreamOptions
    {
        FullDocument = ChangeStreamFullDocumentOption.UpdateLookup
    };

    //The operationType of update, where the document id in collection is current one and the updated field
    //is last login.
    var filter = "{ $and: [ { operationType: 'update' }, " +
                 "{ 'fullDocument._id' : '" + id + "'}" +
                 "{ 'updateDescription.updatedFields.LastLogin': { $exists: true } } ] }";

    var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<BsonDocument>>().Match(filter);

    var changeStream = collectionDoc.Watch(pipeline, options).ToEnumerable().GetEnumerator();

    try
    {
        while (changeStream.MoveNext())
        {
            var next = changeStream.Current;
            Debug.WriteLine("PRINT-OUT:" + next.ToJson());
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine("PRINT-OUT: " + ex);
    }
    finally
    {
        changeStream.Dispose();
    }
}