Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate Queryable<T> back to IMongoQuery

Tags:

c#

linq

mongodb

Consider the following code

var q = from e in myCollection.AsQueryable<Entity>() where e.Name == "test" select e;

The actual query is very complex and I don't like building it using QueryBuilder instead of LINQ.

So I want to convert it back to IMongoQuery to use in myCollection.Group() call since there is no GroupBy support through LINQ.

Is it possible?

like image 625
Vladimir Mischenko Avatar asked Apr 21 '12 17:04

Vladimir Mischenko


2 Answers

Edited answer:

I realized that there already is an official way to get the Mongo query from a LINQ query (I should have known!). You have to downcast the IQueryable<T> to a MongoQueryable<T> to get access to the GetMongoQuery method:

var linqQuery = from e in collection.AsQueryable<Entity>() where e.Name == "test" select e;
var mongoQuery = ((MongoQueryable<Entity>)linqQuery).GetMongoQuery();

Original answer:

At the moment there is no officially supported way to do that, but in the near future we do intend to make it easy to find out what MongoDB query the LINQ query was mapped to.

In the short term you could use the following undocumented internal methods to find out what MongoDB query the LINQ query is mapped to:

var linqQuery = from e in collection.AsQueryable<Entity>() where e.Name == "test" select e;
var translatedQuery = (SelectQuery)MongoQueryTranslator.Translate(linqQuery);
var mongoQuery = translatedQuery.BuildQuery();

But at some point you might need to switch from these undocumented methods to officially supported methods (the undocumented methods might change or be renamed in the future).

like image 183
Robert Stam Avatar answered Sep 29 '22 19:09

Robert Stam


A quick extension based on Robert Stam's answer:

public static IMongoQuery ToMongoQuery<T>(this IQueryable<T> linqQuery)
{
    var mongoQuery = ((MongoQueryable<T>)linqQuery).GetMongoQuery();
    return mongoQuery;
}
public static WriteConcernResult Delete<T>(this MongoCollection<T> col,   IQueryable<T> linqQuery)
{
     return col.Remove(linqQuery.ToMongoQuery());
}
public static WriteConcernResult Delete<T>(this MongoCollection<T> col, Expression<System.Func<T, bool>> predicate)
{
    return col.Remove(col.AsQueryable<T>().Where(predicate).ToMongoQuery());
}

example:

myCollection.Remove(myCollection.AsQueryable().Where(x => x.Id == id).ToMongoQuery());
myCollection.Delete(myCollection.AsQueryable().Where(x => x.Id == id));
myCollection.Delete(x => x.Id == id);
like image 34
Elya Livshitz Avatar answered Sep 29 '22 19:09

Elya Livshitz