1

如何从 LINQ 查询中获取生成的查询?我试过了,但没有用:

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();

InstrumentationDocument在哪里

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; }
}
4

2 回答 2

1

您需要从代码中删除 .ToArray() 。目前,查询不是 MongoQueryable 实例。它是一组匿名类型。因此,您对 MongoQueryable 的转换不应该工作。

于 2013-01-03T14:38:10.807 回答
0

它在最新版本的 MongoDB (v2.6) 中要简单得多,只需调用.ToJson()LINQ 查询,然后将查询字符串打印到控制台。

string queryTextSentToMongoDb = query.ToJson();
于 2014-07-25T00:05:42.413 回答