[英]how to build dynamic query in mongodb with various conditions
I have a sql query I need to make equivalent mongodb
query I am using c#
driver. 我有一个SQL查询,我需要使用c#
驱动程序进行等效的mongodb
查询。 Is it possible to create a dynamic method to create mongo equivalent of these kind of sql
queries where I can specify dynamically what all columns should be taken with dynamically created where conditions. 是否有可能创建一种动态方法来创建与此类sql
查询等效的mongo,在这里我可以动态指定在条件动态创建的情况下应采用的所有列。 Please help to create mongo equivalent query using c#
请帮助使用c#
创建mongo等效查询
SELECT distinct(employeeID), firstname, Lastname, salary, joinedOn FROM [Employees]
where salary >= 40000 and joinedOn between '2011/02/25' and '2012/02/27'
What about use Linq to build a dynamic query? 使用Linq构建动态查询又如何呢?
public T findOne<T> (Expression<Func<T, bool>> expression) where T: class
{
var db = server.GetDatabase(databaseName);
var documents = db.GetCollection<T>(typeof(T).Name);
return (documents.AsQueryable<T>().Where(expression)).SingleOrDefault;
}
You can use it in this way: 您可以通过以下方式使用它:
var employee = findOne<Employee>(e=> d.salary>=4000 &&
d.joinedOn > "2011/02/25" &&
d.joinedOn < "2012/02/27");
I think you should convert joinedOn to DateTime. 我认为您应该将joinOn转换为DateTime。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.