Search code examples
c#mongodbmongodb-querymongodb-.net-driver

In mongoDB how to determines whether all elements of a sequence satisfy a condition


"ElemMatch" tests that at least one item in array match the query. I just want to test all items (like Enumerable.All in LINQ)

Query.ElemMatch("Prices", Query.GTE("Value", criteria.MinPrice))

any suggestion will be accepted. (mongo script, ...)


Solution

  • Instead of testing that every element matches the condition, you can use Query.Not to ensure that none of them fail the opposite condition.

    e.g. Where all Values are not less than criteria.MinPrice

    Query.Not(Query.ElemMatch("Prices", Query.LT("Value", criteria.MinPrice)));
    

    This approach will only work if you have a consistent schema where every element in Prices always has a Value, as Prices that don't have a Value won't fail the check.

    If Prices may be empty you may want to exclude those docs

    Query.And(
        Query.Exists("Prices.0"),
        Query.Not(Query.ElemMatch("Prices", Query.LT("Value", criteria.MinPrice)))
    );