Search code examples
c#mongodbmongodb-.net-driver

Query by specific array index


I'm struggling to find the c# equivalent for this query in mongodb:

db.getCollection('content').find({ "MyIntArrayProp.0": { $gt: 100 } })

"MyIntArrayProp" is an integer array property of each document

I'm trying to query for all documents where the MyIntArrayProp array has a value at index 0 > 100.

Is this possible to replicate through the fluent interface or the strongly typed query builder?


Solution

  • Edited answer after question update:

    var results = documents.Where(d => 
        d.MyIntArrayProp?.Count() > 0 && // array not null and has items
        d.MyIntArrayProp[0] > 100); // compare value
    

    If you're absolutely sure the array can never be null and has always at least one item with index 0, then the first part of the predicate can be omitted.