GrandNode
GrandNode

Reputation: 121

Mongodb c# Conditions in query LINQ

My query look like this:

var query = from p in collection
where p.MinStockQuantity >= p.StockQuantity
select p;

I can't run because I have exception: Unsupported filter: ([MinStockQuantity] >= [StockQuantity])

This query also does not work, the same bug.

    var collection = database.GetCollection<Product>("Product");
    var builder = Builders<Product>.Filter;
    var filter = builder.Where(o => o.MinStockQuantity > o.StockQuantity);
    var query = collection.Find(filter).ToListAsync().Result;

How can I compare 2 fields ?

Upvotes: 1

Views: 1817

Answers (2)

sifa vahora
sifa vahora

Reputation: 117

I know I am quite late but this works perfectly,try this :

  var collection = database.GetCollection<Product>("Product");
        var builder = Builders<Product>.Filter;
        var filter = builder.Gt(o => o.MinStockQuantity , o.StockQuantity);
        var query = collection.Find(filter).ToListAsync().Result;

Gt here is greater than. there are various other methods like Gte =greater than equal to etc .

Upvotes: 1

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

So my previous answer was obviously wrong. You shoud use that query

db.products.find({ $where: "this.MinStockQuantity > this.StockQuantity" })

To run this query in c# world you need to use BSON documents:

var doc = MongoDB.Bson.Serialization.BsonSerializer
         .Deserialize<BsonDocument>
         ("{$where: \"this.MinStockQuantity > this.StockQuantity\"}");
var result = collection.Find(new CommandDocument(doc));

I used that query in my test application and it yells proper results.

Upvotes: 0

Related Questions