Search code examples
c#.netlinqmongodbmongodb-.net-driver

Access "_t" element value from LINQ


Is there a way to access the value of the "_t" element in a document when querying with LINQ from MongoCollection.AsQueryable()?

I have tried this:

_collection.AsQueryable()
           .Where(t => t.ToBsonDocument()
                        .GetValue("_t") == "someValue");

but I get the exception:

Unable to determine the serialization information for the expression: BsonExtensionMethods.ToBsonDocument(t).GetValue("_t").


Solution

  • No, you can't access the value in _t directly. You can however use LINQ to query the value using GetType or is:

    _collection.AsQueryable().Where(doc => doc is Hamster);
    _collection.AsQueryable().Where(doc => doc.GetType() == typeof(Squirrel));
    

    This will generate the following queries:

    {
        _t : "Hamster" 
    }
    
    {
        _t : "Squirrel"
    }