1

How can I get the generated query from the LINQ query? I tried this but it didnt work:

var query = (
            from d in mcollection.AsQueryable<InstrumentationDocument>()
            where d.user == User && d.timestamp > DateTime.Today.AddDays(-days)
            orderby d.timestamp descending
            select new
            {
                d.timestamp,
                d.machine,
                d.processID,
                feature = d.info["feature"].AsString,
                extra = d.info.Contains("extra") ? d.info["extra"].ToJson() : ""
            }
);

var mongoQuery = ((MongoQueryable<InstrumentationDocument>)query).GetMongoQuery();

var json = mongoQuery.ToJson();

where InstrumentationDocument is

class InstrumentationDocument
{
    [BsonId]
    public ObjectId _id { get; set; }

    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime timestamp { get; set; }

    public string user { get; set; }
    public string machine { get; set; }
    public int processID { get; set; }
    public BsonDocument info { get; set; }
}
2
  • Did you set a breakpoint on the mongoQuery.ToJson() to read the value of this expression or are you writing it to a log/console? From your code example, it seems like you're not getting the query because there is no variable to read, and it's not being written anywhere. Commented Dec 28, 2012 at 16:08
  • Can you post what query is? We can't really help you unless we have all the details. Commented Dec 28, 2012 at 22:38

2 Answers 2

1

You need to remove .ToArray() from your code. Currently, query is NOT a MongoQueryable instance. It is an array of anonymous types. Hence, your cast to MongoQueryable should NOT be working.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I actually had it without the ToArray in my code. The problem seems to actually be the projection into annonymous type new {} at the end. That type is not an InstrumentationDocument, therefore it cannot cast query into MongoQueryable<InstrumentationDocument>
0

Its much simpler in the latest version of MongoDB (v2.6), just call .ToJson() on the LINQ query, then print the query string to the console.

string queryTextSentToMongoDb = query.ToJson();

1 Comment

Really? Because I would think that would cause the query to execute, and the ToJson() to be the actual results of the query, not the definition of the query that was sent to MongoDb

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.