How to query BsonExtraElements in MongoDB via Linq

2019-05-11 21:45发布

问题:

I used the mongodb [BsonExtraElements] feature to extend my class some dynamic data, but unfortunately I cannot create a query by mongodb C# driver.

Here is my model class:

public class MongoProductEntity 
{
    public MongoProductEntity()
    {
        AdditionalColumns = new BsonDocument { AllowDuplicateNames = false };
    }
    [BsonExtraElements]
    public BsonDocument AdditionalColumns { get; set; }
    public string BrandName { get; set; }
}

Here is the query part:

        var productEntity = new MongoProductEntity ()
        {
            BrandName = "Brand"
        };            
        productEntity.AdditionalColumns.Add("testProperty", 6);
        productEntity.AdditionalColumns.Add("testProperty2", "almafa");

        await productEntityRepo.InsertAsync(productEntity);
        var qq = productEntityRepo.Where(x => x.AdditionalColumns["testProperty"] == 6).ToList();

This query returns no one element from database, however if I'm trying to query the BrandName property everything is working fine!

Is there anyone who faced similar situation or know why that query is not woking? Thx in advance!

Just a short remark here: the type of productEntityRepo is a wrapper over the MongoDb MongoProductEntity collection and this wrapper returns the collection as Queryable, that's all. I'm using MongoDb 3.2.9, with the latest C# Driver 2.2.4.

回答1:

Since version 2.3 of the C# driver it is possible to use the .Inject() method on a FilterDefinition<T>:

var filter = Builders<BsonDocument>.Filter.Eq("testProperty2", "almafa");
productEntityRepo.Where((dbModel) => dbModel.BrandName == "Brand" && filter.Inject());

This should allow you express filters that are difficult, or impossible, to describe via LINQ. You will need to update from 2.2.4 to the newer version though.