![](/img/trans.png)
[英]How do I Serialize and DeSerialize all properties to String using Mongo C# Driver's BSONClassMap
[英]How can I use BsonClassMap to change the way a MongoDB C# Driver class is deserialized?
由於我將過濾器應用於變更流(在SO上討論: 如何從MongoDB中的ChangeStream 過濾對特定字段的更新 ),我得到的是BsonDocument而不是ChangeStreamDocument對象。 此BsonDocument與ChangeStreamDocument的唯一不同之處在於,它包含一個額外的元素,稱為“ tmpfields”。
在我的場景中,我仍然需要文檔中的ResumeToken和其他元素,因此我想將此BsonDocument轉換為ChangeStreamDocument對象。 我的第一次嘗試是使用BsonSerializer.Deserialize<ChangeStreamDocument<BsonDocument>>( doc)
,其中doc是我返回的BsonDocument。 但是,由於它具有額外的tmpfields元素,因此不允許這樣做。
我嘗試注冊BsonClassMap,因為ChangeStreamDocument類是C#驅動程序的一部分,並且無法將[BsonIgnoreExtraElements]屬性添加到該類中,但是我沒有成功:
BsonClassMap.RegisterClassMap<ChangeStreamDocument<BsonDocument>>(cm =>
{
cm.AutoMap();
cm.SetIgnoreExtraElements(true);
});
AutoMap()
不能正常工作,但是我遇到了一個“找不到匹配的創建者”的例外。 我嘗試了cm.MapCreator(...)
,但是那里也沒有成功。 我將AutoMap()
調出(只離開了SetIgnoreExtraElements行),並收到有關無法匹配屬性(_id等)的錯誤。 因此,我為每個屬性嘗試了諸如cm.MapProperty(c => c.DocumentKey).SetElementName("documentKey")
之類的行,但是當我使用Deserialize()
方法時,它們從未設置過-它們留為null。
現在,我已恢復使用doc["field"].AsXYZ
方法從BsonDocument獲取所需的值,但是我想學習一種更好的方法。
使用RegisterClassMap是否正確? 如果是這樣,我想念什么?
我無法將[BsonIgnoreExtraElements]屬性添加到該類
如果您只是想忽略多余的字段。 您可以添加一個額外的聚合管道$project
來刪除該字段。
例如
var options = new ChangeStreamOptions { FullDocument = ChangeStreamFullDocumentOption.UpdateLookup };
var addFields = new BsonDocument { { "$addFields", new BsonDocument { { "tmpfields", new BsonDocument { { "$objectToArray", "$updateDescription.updatedFields" } } } } } };
var match = new BsonDocument { { "$match", new BsonDocument { { "tmpfields.k", new BsonDocument { { "$nin", new BsonArray{"a", "b"} } } } } } };
// Remove the unwanted field.
var project = new BsonDocument { {"$project", new BsonDocument { {"tmpfields", 0 } } } };
var pipeline = new[] { addFields, match, project };
var cursor = collection.Watch<ChangeStreamDocument<BsonDocument>>(pipeline, options);
var enumerator = cursor.ToEnumerable().GetEnumerator();
while(enumerator.MoveNext())
{
ChangeStreamDocument<BsonDocument> doc = enumerator.Current;
Console.WriteLine(doc.DocumentKey);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.