1

I have an object similar to the one below in C#. I would like to find matching person objects that contain an item matching a provided type and that item's sourceId is also present in an array of provided sourceIds:

Person: {
  id: 1,
  items: [
    {
      type: "one",
      sourceId: 2
    },
    {
      type: "two"
      sourceId: 3
    }
  ]
}

So far I have come up with this:

var filter = Builders<Person>.Filter.In(p => p.items.Where(i => i.type == "one").FirstOrDefault().sourceId, providedIds);
var results = PersonCollection.FindAsync(filter);

When I run, I get this error:

Unable to determine the serialization information for p => p.items.Where(i => (i.type == "one")).FirstOrDefault().sourceId

From what I can have been able to find, it seems that the Mongo driver doesn't understand FirstOrDefault (or perhaps Where as well). How might I accomplish this query?

1 Answer 1

2

MongoDB .NET driver is not able to interpret your filter and translate it into MongoDB query language.

You have to use $elemMatch instead and the filter can look like this:

{ "items" : { "$elemMatch" : { "type" : "one", "sourceId" : { "$in" : [1, 2, 3] } } } }

C# version:

var filter = Builders<Person>.Filter.ElemMatch(f => f.items,
            item => item.type == "one" && providedIds.Contains(item.sourceId));

which generates exactly the same $elemMatch statement I pasted above

Sign up to request clarification or add additional context in comments.

Comments

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.