MongoDB C# 2.x Driver ElemMatch with Dictionaries MongoDB C# 2.x Driver ElemMatch with Dictionaries mongodb mongodb

MongoDB C# 2.x Driver ElemMatch with Dictionaries


Well, after some trial and error implementations, I figured out a way to do what I needed. Instead of directly using my model class, I ended up using a BsonDocument collection just for my ElemMatch filter like this:

var bsonCollection = database.GetCollection<BsonDocument>("testcollection");

The filter gets created like this:

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

And the generic BsonDocument can be deserialized back to my model class using BsonSerializer:

var foundDoc = BsonSerializer.Deserialize<Document>(bsonCollection.Find(filter).Limit(1).FirstOrDefault());