3

我正在尝试使用 ElemMatch 使用 2.2 驱动程序在 MongoDB 中查找文档,但没有成功。我收到一个异常,例如:

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 驱动程序中完美运行。

有谁知道我做错了什么?

4

1 回答 1

3

好吧,经过一些反复试验后,我找到了一种方法来做我需要的事情。我最终没有直接使用我的模型类,而是为我的 ElemMatch 过滤器使用了一个 BsonDocument 集合,如下所示:

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)));

并且可以使用 BsonSerializer 将通用 BsonDocument 反序列化回我的模型类:

var foundDoc = BsonSerializer.Deserialize<Document>(bsonCollection.Find(filter).Limit(1).FirstOrDefault());
于 2016-01-04T23:58:10.170 回答