我试图使用ElemMatch在MongoDB中使用2.2驱动程序找到一个文档,但没有成功。我收到一个例外情况,例如:
System.InvalidOperationException :字段'EnabledForProduct‘的序列化程序必须实现IBsonArraySerializer并提供项序列化信息。
我的课是这样的:
public class Document
{
public string Id {get; set;}
public Dictionary<Product, bool> EnabledForProduct { get; set; }
}
public enum Product {Product1,Product2};
我的ClassMap看起来像这样:
BsonClassMap.RegisterClassMap<Document>(cm =>
{
cm.AutoMap();
cm.MapMember(c => c.EnabledForProduct)
.SetSerializer(new DictionaryInterfaceImplementerSerializer<Dictionary<Product, bool>>(DictionaryRepresentation.ArrayOfDocuments,
BsonSerializer.LookupSerializer<int>(),
BsonSerializer.LookupSerializer<bool>()));
});
当尝试使用筛选器时会出现异常,例如:
Builders<Document>.Filter.ElemMatch(f => f.EnabledForProduct,
x => x.Key == Product1 && x.Value))
这过去在1.x驱动程序中是完美无缺的。
有人知道我做错了什么吗?
发布于 2016-01-04 23:58:10
嗯,经过一些尝试和错误实现之后,我想出了一种方法来做我需要的事情。我没有直接使用模型类,而是使用了一个BsonDocument集合,只用于ElemMatch过滤器,如下所示:
var bsonCollection = database.GetCollection<BsonDocument>("testcollection");
过滤器的创建方式如下:
var filter = Builders<BsonDocument>.Filter.ElemMatch("EnabledForProduct", Builders<BsonDocument>.Filter.And(Builders<BsonDocument>.Filter.Eq("k",(int)Product.Product1),Builders<BsonDocument>.Filter.Eq("v",true)));
并且可以使用BsonDocument将泛型BsonSerializer反序列化回模型类:
var foundDoc = BsonSerializer.Deserialize<Document>(bsonCollection.Find(filter).Limit(1).FirstOrDefault());
https://stackoverflow.com/questions/34541589
复制相似问题