如何使用查找复杂搜索查询的位置?



我有一个产品模型,其中包含一个列表,我需要找到产品并根据语言进行过滤。

return Collection.Find(p => p.ProductValues.Where(pv => pv.Lang == lang)).toList();
我得到的错误是
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<TestMongodb.Entities.ProductValue>' to 'bool'

我的模型是

public class Product : BaseEntity
{
public Product(string price, string date, List<ProductValue> value) =>
(Price, Date, ProductValues) = (price, date, value);
public string Price { get; set; }
public string Date { get; set; }
[BsonElement("value")]
public List<ProductValue> ProductValues { get; set; }
}

public class ProductValue
{
public ProductValue(string lang, string name, string description) =>
(Lang, Name, Description) = (lang, name, description);
[BsonElement("lang")]
public string Lang { get; }
[BsonElement("name")]
public string Name { get; }
[BsonElement("description")]
public string Description { get; }
}

Any()代替Where()

return Collection.Find(p => p.ProductValues.Any(pv => pv.Lang == lang));

为什么Any()优于Where()?

  • Where(<predicate>)子句用于根据传递给它的谓词进行过滤。它返回一组新的过滤记录,而不是true/false值。

Any(<predicate>):如果谓词满足条件,Any()返回true/false。'

现在,Find根据返回布尔值true的条件返回文档,而不是新列表。这就是为什么我们使用Any()而不是Where()

最新更新