lapsus
lapsus

Reputation: 3055

c# MongoDb filter on List<T>.Count

Let the code speak for itself ;-)

public class SampleObject
{
    public List<string> SampleStrings {get;set;}
}

MongoDb related code:

// filter on SampleStrings.Count < 5
var filter = Builders<SampleObject>.Filter.Lt(so => so.SampleStrings.Count, 5)

Unhandled Exception: System.InvalidOperationException: Unable to determine the serialization information for so=> so.SampleStrings.Count.

Count() won't work either. Is there a MongoDb way? Maybe one that perfectly integrates within the IFluent interface?

Upvotes: 2

Views: 419

Answers (1)

thepirat000
thepirat000

Reputation: 13124

Try with this:

var filter = Builders<SampleObject>.Filter.Not(
                      Builders<SampleObject>.Filter.Exists(so => so.SampleStrings[4]));

This will get translated into the following mongo db filter query:

"SampleStrings.4" : { "$exists" : false }

Saying that the element at index 4 should not exists is equivalent to say the count of elements should be less than 5.

Upvotes: 1

Related Questions