You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB查询报错:如何筛选currentprice低于expectedprice一半的Sale数据?

解决MongoDB C#驱动筛选currentprice低于expectedprice一半的问题

错误原因

你的currentprice和expectedprice都是long整数类型,原代码中用0.5做乘法会触发隐式类型转换为double,但MongoDB LINQ驱动无法序列化这个浮点常量,导致抛出ExpressionNotSupportedException。

解决方案

方案1:改用整数运算(推荐)

将条件转换为currentprice * 2 < expectedprice,全程用整数运算,既避免类型转换问题,也不会有浮点精度损失,同时MongoDB能更好地利用相关索引:

public List<Sale> GetDeals()
{
    var collection = _database.GetCollection<Sale>("listOfSales");
    var filter = Builders<Sale>.Filter.Where(sale => sale.currentprice * 2 < sale.expectedprice);
    return collection.Find(filter).ToList();
}

方案2:使用MongoDB原生操作符构造过滤器

通过Builders<Sale>.Expression显式构造乘法操作,让驱动正确识别表达式逻辑:

public List<Sale> GetDeals()
{
    var collection = _database.GetCollection<Sale>("listOfSales");
    var filter = Builders<Sale>.Filter.Lt(
        sale => sale.currentprice,
        Builders<Sale>.Expression.Multiply(sale => sale.expectedprice, 0.5)
    );
    return collection.Find(filter).ToList();
}

方案3:使用聚合管道

适合更复杂的查询场景,通过$expr在$match阶段执行字段间的计算比较:

public List<Sale> GetDeals()
{
    var collection = _database.GetCollection<Sale>("listOfSales");
    var pipeline = new BsonDocument[]
    {
        new BsonDocument("$match",
            new BsonDocument("$expr",
                new BsonDocument("$lt",
                    new BsonArray { "$currentprice", new BsonDocument("$multiply", new BsonArray { "$expectedprice", 0.5 }) }
                )
            )
        )
    };
    return collection.Aggregate<Sale>(pipeline).ToList();
}

内容的提问来源于stack exchange,提问作者LexxTal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:06:05