3

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.

1 Answer 1

2

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"))
Sign up to request clarification or add additional context in comments.

1 Comment

Ah great! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.