zaq
zaq

Reputation: 2661

Create an In filter against an array field of Mongodb using c#

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?

Upvotes: 1

Views: 68

Answers (1)

mickl
mickl

Reputation: 49945

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

Upvotes: 2

Related Questions