Linq to MongoDB Filter

こ雲淡風輕ζ 提交于 2019-12-24 00:58:24

问题


I have a MongoDB collection, listed below:

{ 
    "_id" : ObjectId("001"), 
    "ticker" : "MSFT=US", 
    "exchange" : "OTC", 
    "localtick" : "MSFT", 
    "compname" : "Microsoft", 
    "currency" : "USD", 
    "insertedtime" : ISODate("2016-06-13T23:10:09.341+0000")
}
{ 
    "_id" : ObjectId("002"), 
    "ticker" : "TSLA=CA", 
    "exchange" : "TSX", 
    "localtick" : "TSLA", , 
    "compname" : "Tesla", 
    "currency" : "CAD", 
    "insertedtime" : ISODate("2016-06-13T23:10:09.809+0000")
}

But when I try to do a filter in my query:

var documents = collection.AsQueryable()
            .Where(c => c["ticker"].ToString().Contains("=CA"));

I get the following error:

Unsupported filter: {document}{ticker}.ToString().Contains("=CA").

What should I be doing to get MongoDB to handshake with LINQ?


回答1:


Use a strongly-typed collection when using LINQ queries:

public class Test
{
    public ObjectId _id;
    public string ticker;
    public string exchange;
    public string localtick;
    public string compname;
    public string currency;
    public DateTime insertedtime;
}

var query = db.GetCollection<Test>("test")
    .AsQueryable()
    .Where(c => c.ticker.Contains("=CA"));


来源:https://stackoverflow.com/questions/37800826/linq-to-mongodb-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!