Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query BsonExtraElements in MongoDB via Linq

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.

like image 276
Vajda Endre Avatar asked Oct 11 '25 21:10

Vajda Endre


1 Answers

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.

like image 63
Bjorn De Rijcke Avatar answered Oct 14 '25 10:10

Bjorn De Rijcke