【问题标题】:MongoDB C# - filter for findig object by contiditon in nested arrayMongoDB C# - 在嵌套数组中按条件查找对象的过滤器
【发布时间】:2021-04-16 04:57:54
【问题描述】:

我在构建过滤器以按条件在嵌套数组中获取对象时遇到问题。

我的模型是:

public class ProductPriceInStore
{
    [BsonId]
    public ObjectId Id { get; set; }

    public ObjectId store { get; set; }

    public ObjectId product { get; set; }

    public string measurementUnit { get; set; }

    public IList<ProductPrices> prices { get; set; }
}

 public class ProductPrices
{
    public double? actualPrice { get; set; }
  
    public double? originalPrice { get; set; }
}

我想要做的是找到所有 ProductPriceInStore,其中包含 ProductPrice 且实际价格大于 originalPrice

我在我的项目中使用 nugget MongoDB.Driver 2.7.3

【问题讨论】:

  • ElemMatch
  • 我试着像这样使用它 var filter = Builders.Filter.ElemMatch(y => y.prices, x => x.actualPrice > x.originalPrice);但它给了我错误'不支持的过滤器:({document}{actualPrice} > {document}{originalPrice})。我将不得不进一步研究 elementMatch

标签: c# .net mongodb mongodb.driver


【解决方案1】:

您可以使用 Linq 查询选择器: 如果您有 ProductPriceInStore 列表,那么您可以这样做:

ProductPriceInStoreList.Where(item => item.prices.Where(p => p.actualPrice  > p.originalPrice   ))

【讨论】:

  • 我拥有它就像一个 IMongoCollection。我可以以某种方式使用 .Find 方法 ant 访问 linq,然后我不知道如何定义它,它通常会导致驱动程序无法翻译命令的错误。而且我无法将该集合加载到内存中 - 我的意思是“.toList”,因为该集合有超过 5 000 000 条记录...
【解决方案2】:

您可以使用以下聚合管道获得所需的结果,因为 $elemMatch 不能用于比较嵌套对象中的字段值 (afaik)。

db.ProductPriceInStore.aggregate(
[
    {
        $set: {
            prices: {
                $filter: {
                    input: "$prices",
                    cond: { $gt: ["$$this.actualPrice", "$$this.originalPrice"] }
                }
            }
        }
    },
    {
        $match: {
            prices: { $gt: [0, { $size: "$prices" }] }
        }
    }
])

然而这不会有效。更好的方法是让您在创建/保存嵌套项时存储布尔属性 IsGreaterThanOriginalPrice,在这种情况下,您可以轻松使用 ElemMatch 而不会有太多麻烦。

【讨论】:

    【解决方案3】:
    db.ProductPriceInStore.find({$expr:{$gt:["$prices.actualPrice", "$prices.originalPrice"]}})
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 2019-12-18
      • 2018-08-08
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      相关资源
      最近更新 更多