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

Lambda where fails but string where works


Using the old MongoDB driver, I was able to perform the following query:

Query.Where("this.plan.sstats.used < this.plan.sstats.available")

But with the new one, I'm forced to write this:

builder.Filter
      .Where(t => t.Plan.StorageStats.UploadUsed < t.Plan.StorageStats.UploadAvailable)

These look the same, but the new one does not work and I receive this error message:

Additional information: Unsupported filter: ({plan.sstats.used} < {plan.sstats.available}).

The back-end version is currently the same, so I don't see any reason why this shouldn't continue to be able to work.

How do I fix this? Is there a better way of doing this, whilst maintaining atomicity?


Solution

  • Seems MongoDb drive doesn't support it any more. Me personally see two possible solutions:

    1) You query bson, not your objects, that should work (i have tried with my sample data out):

    FilterDefinition<BsonDocument> filter = 
        new BsonDocument("$where", "this.plan.sstats.used<this.plan.sstats.available");
    

    Waht is bad on this approach: your should query your collection as BsonDocument collection.

    2) You query your collection as ToEnumerable() and than just add your filter as Where linq statement. That will work too, but you loose querying data directly on mongodb.

    3) You could use aggregation framework, i did it this way:

    var result = collection.Aggregate()
            .Group(r => r.Plan.StorageStats.UploadUsed - r.Plan.StorageStats.UploadAvailable,
                  r => new {r.Key, Plans= r.Select(t=>t.Plan)} )
            .Match(r=>r.Key < 0)
            .ToEnumerable()
            .SelectMany(r=>r.Plans);
    

    Negative on aggregate is that you couldn't combine it with your other Filters you use in Find() call.