How do I get a property from an object in a dictionary in a MongoDB document?
Our Mongo data looks like this:
{
"_id" : ObjectId("542d881b8bc641bbee1f8509"),
"ExtendedProperties" : {
"Context" : {
"_t" : "LoggingContext",
"DeclaringTypeName" : "EndpointConfig"
}
}
}
In C # code, ExtendedProperties are represented as follows:
public class LogEntry
{
public IDictionary<string, object> ExtendedProperties { get; set; }
}
I've tried every method I can find to be able to query for the DeclaringTypeName value. Nothing seems to work, as shown in the following code:
// 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)));
For clarity, I've researched every StackOverflow, CodePlex, and Mongo.org thread I can find and still haven't been able to solve it correctly.
Naturally, this will be what I am doing wrong.
Someone please throw me a bone.
+3
source to share
1 answer
I have defined the LogEntry class as
public class LogEntry
{
public ObjectId Id { get; set; }
public IDictionary<string, object> ExtendedProperties { get; set; }
}
then I inserted a sample document
var log = new LogEntry
{
ExtendedProperties = new Dictionary<string, object>
{
{
"Context", new LoggingContext
{
DeclaringTypeName = "EndpointConfig"
}
}
}
};
collection.Insert(log);
then I ran the query:
var rawQuery = Query.EQ("ExtendedProperties.Context.DeclaringTypeName", "EndpointConfig");
var query = new List<IMongoQuery>();
query.Add(rawQuery);
var rawResult = collection.Find(rawQuery).ToList();
request will send mongo on request
db.messages.find({ "ExtendedProperties.Context.DeclaringTypeName" : "EndpointConfig" })
And I got the result
+1
source to share