How to translate query from SQL to MongoDB C# Driver: Like, Distinct and Top - mongodb-.net-driver

My SQL query looks like:
from attr in Attributes
where attr.Value.Contains("444")
select attr.Value).Distinct().Take(100).ToList();
I have tried with something like that but i dont know where use the "SetLimit(n)" function here:
IMongoQuery likeValueQuery = Query.Matches("Value", "/444/");
var result = Attributes.Distinct("Value", likeValueQuery);
Regards.

Related

how can I use like query in ruby with sinatra?

Here's the query I tried:
#blogs = DB[:blogs].where(:title => params[:s_txt]).reverse_order(:id)
In this query, I'd like to find blogs in my database. I also need to create a query that gives users more results. How can I do this?
It is better to use dynamic parameters to avoid SQL injection:
#blogs = DB[:blogs].where("title LIKE ?", "%#{params[:s_txt]}%").reverse_order(:id)
or
#blogs = DB[:blogs].where("title LIKE :text", text: "%#{params[:s_txt]}%").reverse_order(:id)
You can easily add more parameters to this:
#blogs = DB[:blogs].where("title LIKE ? OR content LIKE ?", "%#{params[:s_txt]}%", "%#{params[:s_txt]}%").reverse_order(:id)
or
#blogs = DB[:blogs].where("title LIKE :text OR content LIKE :text", text: "%#{params[:s_txt]}%").reverse_order(:id)
I also had this problem and only found this solution
#blogs = DB[:blogs].where("title LIKE '%#{params[:s_txt]}%'").reverse_order(:id)
Curious if there are better ways..
Searching in two fields is repeating the LIKE and seperating by AND or OR
#blogs = DB[:blogs].where("title LIKE '%#{params[:s_txt]}%'
or comment LIKE '%#{params[:c_txt]}%'").reverse_order(:id)
or do it like this
#blogs = DB[:blogs].where("title||comment LIKE '%#{params[:s_txt]}%'").reverse_order(:id)
Tested in Sqlite and it works. One advise: in lage tables you 'd better drop the first % if possible because the database will do a full table scan otherwise without using indexes but you can find all that stuff in the sql questions.

Dynamic Linq to add LIKE to where clause

I'm trying to perform a LIKE clause in an entity query. The examples I've seen use dynamic linq to do this kind of thing, but my code...
var query = context.StudySet
.Where("it.PatientName LIKE #patientName", new ObjectParameter("patientName", patientName);
...gives me a System.Linq.Dynamic.ParseException with
Additional information: Expression of type 'Boolean' expected
context is a DbContext from EF 6 code-first, patientName is a string
Please tell me what's wrong with my code?
if you want use DynamicLINQ you need change your code like this
var query = context.StudySet.Where("it.PatientName.Contains(#0)", patientName);
because DynamicLinq can't parse LIKE operator
I've realised my mistake.
I had assumed the method to pass the query was part of Dynamic Linq but actually it's just a variant of the standard Where method on ObjectQuery. If I get the ObjectContext from my (code first) DbContext it's all good.
ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
ObjectSet<Study> studySet = objectContext.CreateObjectSet<Study>();
var query = studySet.
Where("it.PatientName LIKE #patientName", new ObjectParameter("patientName", patientName));
I don't know of a way to use like with a LINQ query, but you could use a raw SQL query:
var query = context.StudySet.SqlQuery(
"select * from StudySet where PatientName LIKE #patientName",
new SqlParameter("#patientName", patientName));

using linq query with stringBuilder

I want to create dynamic where clause in a LINQ query. I have one stringbuilder sb having append values Country=null || City=null || State=null and one datatable that has column named Name, Lastname, Country, City, State. I want to compare sb values with datatable columns and get null / empty rows.
So I want a LINQ query like this:
var query = from p in datatable.AsEnumerable()
where sb.tostring() // ------------error
select p
but it returns an error. How can I solve this problem?
You can use Dynamic Linq
var query = datatable.Where("Country==null || City==null || State==null");
You'll need to download and include the C# file in the link and add:
using System.Linq.Dynamic;
You can't do that in LINQ. Dynamic LINQ might help you, but that's probably no the best solution for you.
Why are you creating the query as a string? You can just build the query itself dynamically. Have a look at PredicateBuilder.

convert linq to object query to sql query (no linq to sql code or datacontext)

How can i convert linq to object query or any other Func delegate to string like sql statements
for example
var cat_list = new List<Cat> { ... };
var myquery = cat_list.Where(x => x.Age > 2 && x.Name.Contains("Kitty"));
Now myquery is IEnumerable<Cat>. how can i convert this to simply something like this
"Age > #p1 AND Name LIKE #p2"
how can i achieve this ??
Doing something like that is not simple. Have a look at the series of articles Building an IQueryable provider by Matt Warren. All the code he uses is available as a library too. That should help you get started.
You could write an expression tree parser and generate the sql. Your description contains a fault - myquery isn't IQueryable<Cat>, it is an IEnumerable<Cat>. As you tagged it correctly, this is linq-to-objects, not linq-to-sql. There is no information in the calls to construct a query.
Check out the method DataContext.GetCommand() which is passed an IQueryable object and returns the DbCommand object that corresponds to the query. The CommandText property of the DbCommand object shows the text of the query.

Extension Method To Take A Dynamically Built Search Expression?

I think we are basically looking for a extension method that could take in an IQueryable and return an IQueryable based on an entire query statement and not just the where statement.
Example of what we would like for a Search Method:
IRepository<Person> repository = new Repository<Person>();
var results = repository.GetQuery().Include("Names").Search([dynamic linq here]);
We currently have where we build a dynamic linq statement inside the where method
IRepository<Person> repository = new Repository<Person>();
var results = repository.GetQuery().Include("Names").Where([dynamic linq here]);
The problem with that approach is that we want to do include SelectMany and Select on the actual dynamic linq query. You cannot use the SelectMany inside a Where method unless you are actually going into sub properties of sub properties. We would like to do something like the following dynamic linq statement.
SelectMany("Names").Where("LastName.Contains(#0)", "Smith").Select("Person")
We solved this issue without having to use a extension method. We were able to use a similar query that works inside a Where method.
So instead of...
SelectMany("Names").Where("LastName.Contains(#0)", "Smith").Select("Person")
We were able to get the same result with the following query that can be inside a Where method.
Where.("Names.Select(LastName).Contains(#0)", "Smith)
Then when just had to add a Contains Aggregate to the Dynamic Linq library.
http://blog.walteralmeida.com/2010/05/advanced-linq-dynamic-linq-library-add-support-for-contains-extension-.html
The SelectMany had sent us off on a wild goose chase!
Checkout this nuget package: NinjaNye.SearchExensions
It enables you to do something like the following:
var repository = new Repository<Person>();
var results = repository.GetQuery().Search(p => p.LastName, "Smith");
Connected to sql this will produce something smilar to the following:
SELECT [Extent1].[Id] AS [Id],
... [other properties],
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE ([Extent1].[LastName] LIKE N'%Smith%')
The query is built using expression trees so the result is clean.
Check out the source code here:
https://github.com/ninjanye/SearchExtensions/

Resources