Search code examples
c#mongodblambdamongodb-.net-driver

c# lambda query to find matching sub-element


var query = Query<MongoData>.EQ(e => e.name, someString);
var entity = collection.FindOneAs<MongoData>(query);

And this returns the MongoData object in collection where the property name matches the string (someString) I send it.

I'd like to add another query to this to also get the entity that matches name and files.author

collection is an List, and files is an List inside of collection.

Currently, I'm doing it the hard way and just looping through entity.files until I find a match, but this is painful.

So given a MongoData List that contains one object with a name of X and an files list that contains an author of Y, I'd like to return this one.


Solution

  • You could probably do it like this and query multiple properties at once:

    var query = Query.And(
        Query<MongoData>.EQ(e => e.name, someString),
        Query<MongoData>.ElemMatch(
            e => e.files,
            q => q.EQ(f => f.author, someAuthorName)
        )
    );
    

    The latter subquery uses the ElemMatch<TValue> query function, which expects an expression returning an enumerable of subobjects, and a function that executes another query on each of those subobjects.