【问题标题】:C# - Change Streams in MongoDB with $matchC# - 使用 $match 在 MongoDB 中更改流
【发布时间】:2018-06-08 13:03:42
【问题描述】:

我正在尝试将 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);
    }
} 

如果我将光标更改为您在下面看到的内容,它可以工作,但是当文档中存在任何 _id 的活动时,它会返回世界并返回更改流。这不是我想要的。

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

【问题讨论】:

    标签: c# mongodb changestream


    【解决方案1】:

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

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

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

    {
        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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      相关资源
      最近更新 更多