如何从MongoDB文档中的字典中的对象检索属性?

时间:2014-12-12 21:38:31

标签: c# mongodb mongodb-.net-driver

我们的Mongo数据如下所示:

{
        "_id" : ObjectId("542d881b8bc641bbee1f8509"),
        "ExtendedProperties" : {
                "Context" : {
                        "_t" : "LoggingContext",
                        "DeclaringTypeName" : "EndpointConfig"
                }
        }
}

在C#代码中,ExtendedProperties表示如下:

public class LogEntry
{
    public IDictionary<string, object> ExtendedProperties { get; set; }
}

我已经尝试了我能找到的每个方法都可以查询DeclaringTypeName的值。似乎没有任何作用,如下面的代码所示:

// This throws an UnsupportedOperationException with the following message:
// Unable to determine the serialization information for the expression: (LogEntry e) => e.ExtendedProperties.get_Item("DeclaringTypeName").ToString().
query.Add(Query<LogEntry>.EQ(e => ((LoggingContext)e.ExtendedProperties["Context"]), this.DeclaringTypeName ));

// This returns zero matching rows:
query.Add(Query.EQ("ExtendedProperties.Context.DeclaringTypeName", this.DeclaringTypeName));

// This returns zero matching rows:
query.Add(Query.ElemMatch("ExtendedProperties.Context", Query.EQ("DeclaringTypeName", this.DeclaringTypeName)));

// This reports that ExtendedProperties must implement a specific interface and must not return null:
query.Add(Query<LogEntry>.ElemMatch(e => e.ExtendedProperties, qb => Query.EQ("Context.DeclaringTypeName", this.DeclaringTypeName)));

为清楚起见,我已经研究了我能找到的每个StackOverflow,CodePlex和Mongo.org线程,但仍然无法正确解决这个问题。

当然,这将是我做错的事情。

有人请给我一个骨头。

1 个答案:

答案 0 :(得分:1)

我将LogEntry类定义为

public class LogEntry
{
    public ObjectId Id { get; set; }
    public IDictionary<string, object> ExtendedProperties { get; set; }
}

然后我按

插入了示例文档
var log = new LogEntry
{
    ExtendedProperties = new Dictionary<string, object>
    {
        {
            "Context", new LoggingContext
            {
                DeclaringTypeName = "EndpointConfig"
            }
        }
    }
};

collection.Insert(log);

然后我通过以下方式执行查询:

var rawQuery = Query.EQ("ExtendedProperties.Context.DeclaringTypeName", "EndpointConfig");
var query = new List<IMongoQuery>();
query.Add(rawQuery);

var rawResult = collection.Find(rawQuery).ToList();

查询将在查询

下发送mongo
db.messages.find({ "ExtendedProperties.Context.DeclaringTypeName" : "EndpointConfig" })

我得到了结果