0

I have a model such as:

{
  nestedArray1: [
    {
      nestedArray2: [
        {
          id: 1
        }
      ]
    }
  ]
}

I am trying to get the items which contain nestedArray2 with the id value that is among the list x = [1, 2, 3, 4, 5, ...].

I tried to run the following query with no avail:

var query = model.AsQueryable().Where(m => m.nestedArray1.Any(s => s.nestedArray2.Any(m => ids.Any(id => id == m.id))));
var results = query.ToListAsync();

It says that any filter is unsupported.

What is the proper way of writing such a query using Linq?

NOTE:

Here is how I can do it using Mongo query syntax:

db.getCollection('model').find({
    "nestedArray1": {
        $elemMatch:{
            nestedArray2:{
                $elemMatch:{
                  "id" : {$in: [1, 2, 3, 4, 5] }
            }
        }
    }
}

})

And here is how I can do it using C# without Linq query syntax:

var ids = new List<int>() { 1, 2, 3, 4, 5};
var filter = new FilterDefinitionBuilder<Model>()
        .ElemMatch(p => p.nestedArray1, new FilterDefinitionBuilder<NestedModel1>()
            .ElemMatch(s => s.nestedArray2, new FilterDefinitionBuilder<NestedModel2>()
                .In(m=> m.id, ids)));
return await Collection.Find(filter).ToListAsync();
3
  • Any() returns a bool. You want to filter, so to me it is unclear what your desired output is. Could you give an example? Commented Aug 2, 2019 at 11:32
  • @iSpain17 Editted the original post to include the full query syntax. Commented Aug 2, 2019 at 11:51
  • I think we are gonna need the FindAsync<T> definition if Tim's answer doesn't work. Commented Aug 2, 2019 at 11:58

1 Answer 1

2

According to your model the items of nestedArray2 only have a field with one ID.

So considering your example above, you should have something like this (i think):

var query = model.AsQueryable().Where(m => m.nestedArray1.Any(s => s.nestedArray2.Any(m => ids.Contains(m.id))));
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.