Take the 2-minute tour ×

Trying to figure out how to access nested array properties when using the strongly typed query builders for mongodb in c#. Lets say I have the following classes:

public class V {
    public Guid _id { get; set; }
    public List<S> S { get; set; }

public class S {
    public Guid I { get; set;}
    /* other fields */

V is the document type. I want to build a query like this:

var id = Guid.NewGuid();
var query = Query<V>.EQ(v => v.S.I, id);

However that doesn't compile because the S property on V is a List. The resulting mongo query that I would look like to see is this (actual guid syntax is not correct, but the left side is the important part:

{ "S.I": "99ebc751-c12a-4873-8c3f-cb510b26a082" }

How do I do this?

share|improve this question
var query = Query.EQ("S.I", id); ? –  Nuk Nuk San Mar 5 '13 at 18:38
I'm trying to do it without strings, using the strongly typed builders –  Ted Elliott Mar 7 '13 at 16:41
add comment

1 Answer

You'll need to do it as Nuk Nuk mentioned in a comment to your question. Alternatively, you can use ElemMatch (docs.mongodb.org/manual/reference/operator/elemMatch) which is possibly more appropriate anyways.

If you have a suggestion on how we could support this using typed syntax, please give some feedback. For the same reason, we are struggling with how to support the positional ($) update operator.

share|improve this answer
I had written my own set of helper methods before I knew about this that took an expression and gave you back the string property representation of it. But I was trying to switch to the more official version, since I figured it would support more of the custom mapping options. In my implementation I created two extension methods for my scenario and the positional operator. I just look for those extensions when I parse the expression. I considered triggering off FirstOrDefault or similar methods, but I thought that might not be very intuitive. I can send you my helpers if you want. –  Ted Elliott Mar 7 '13 at 16:47
I'd love to know what the names of the methods are? That is really our only issue. We have debated on Member(), Element(), etc... –  Craig Wilson Mar 7 '13 at 16:52
AnyItem and MatchedItem(for $) –  Ted Elliott Mar 8 '13 at 2:38
Actually after thinking about, I think you should look for projection, since that is essentially what it is. Example: v => v.S.Select(s => s.I.J.K), would turn into "S.I.J.K". You would still need something for the positional update operator I think, since there's nothing that really corresponds in the language. –  Ted Elliott Mar 8 '13 at 13:52
@CraigWilson - +1 on the name "Member". Although down the line I can see folks wanting to access a function on a type too. –  Nuk Nuk San Mar 19 '13 at 16:18
add comment

Your Answer


