Search code examples
c#mongodblinqmongodb-.net-driver

Mongodb C# FindAsync. Filter on list inside document using linq


I have a mongodb and I want to filter on a value inside a list in my documents.

My documents looks something like this:

{"_id": "guid" , "mylist": {"stuff": "a", "morestuff": "b"} }

I would like to find a document where "stuff" inside "mylist" is "a" by using linq expressions in FindAsync method.

My best effort so far:

collection.FindAsync(item => item.mylist.Where(item2 => item2.stuff == "a") )

Unfortunatly C# will not accept this statement and i am getting the following errors:

Cannot implicitly convert type "System.Collections.Generic.IEnumerable" to "bool"

Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type"

I am relatively new to linq and have mostly been using resharper to do them for me, so I am probably missing something very basic here.


Solution

  • Sorry, i misanderstood your question, you just should replace Where (that gives you collection of items that pass to your expression) with Any that gives true back if there is any item in collection for that expression is true.

    Use following query:

    collection.FindAsync(Builders<YourClass>.Filter.ElemMatch(
                                         f=>f.mylist, item2=>item2.stuff=="a"))
    

    I think, this one will work too:

    collection.FindAsync(x=>x.mylist.Any(b=>b.stuff=="a"))