0

When running my application I have to write to screen raw query used.

Is any method/extension method available, to get from this:

IQueryable alldata = hr.GetCollection"EventsReceiver").AsQueryable().Where(q => q.UserId == "123");

something similar to:

db.EventsReceiver.find({ "userid" : "123" });
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
user603483
  • 43
  • 6

2 Answers2

0

For anyone having same question I'll repost here Craig's answer on github:

var queryObject = ((IMongoQueryable)alldata).GetQueryObject();

this should give you back the object used to generate the query.

Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
user603483
  • 43
  • 6
0

From FluentMongo v1.2.0.0, there's no public way to expose the query (so sad). Here's a dirty extension method to get at it.

BUT since this is using reflection to get at non-public members don't expect that it will necessarily work in the future.

public static class MongoQueryableExtensions
{
    public static BsonDocument GetMongoQuery<T>(this IQueryable<T> query)
    {
        if(query == null) throw new ArgumentNullException("query");
        Assembly fluentMongoAssembly = typeof(FluentMongo.Linq.MongoCollectionExtensions).Assembly;
        Type mongoQueryableType = fluentMongoAssembly.GetType("FluentMongo.Linq.IMongoQueryable");

        BsonDocument queryDocument = null;
        if(mongoQueryableType.IsAssignableFrom(query.GetType()))
        {
            MethodInfo m = mongoQueryableType.GetMethod("GetQueryObject");
            object queryObject = m.Invoke(query, null);

            PropertyInfo queryProperty = fluentMongoAssembly.GetType("FluentMongo.Linq.MongoQueryObject").GetProperty("Query");
            queryDocument = (BsonDocument)queryProperty.GetValue(queryObject, null);
        }
        return queryDocument;
    }
}
Jason Morse
  • 6,204
  • 5
  • 29
  • 29
  • isn't this a way? http://stackoverflow.com/questions/10261156/translate-queryablet-back-to-imongoquery?lq=1 – Shy Peleg Aug 18 '15 at 14:02