【问题标题】:MongoDB aggregation sum untill with condition (if/else) OR count price and quantity problemMongoDB 聚合求和直到条件(if/else)或计算价格和数量问题
【发布时间】:2019-10-28 03:03:42
【问题描述】:

问题

我正在编写一个可以根据请求的quantity 计算avg price 和整个value 的函数,例如:

async funcName (first_100) {
        let market_quantity = await auctions_db.aggregate([
            {
                $match: {
                    item: 9999,
                }
            },
            {
                $sort: {
                    price: 1
                }
            },
            //RESULT
        ]);
}

//结果

此时我有以下文档:

{
    item_id: 9999,
    price: 1..Number
    quantity: 1..200
    value: price x quantity //it's not virtual field
},{
    another doc...
}

正如我上面提到的,我想要它是 $sum price 字段,直到 quantity 不会达到 100 或 100+(或任何其他数字取决于函数参数)。

我不需要 $sum 前 100 个文档(按 price 升序排序,在这种情况下我会使用 .limit

所以很明显我有两种方法可以做到这一点。至于现在我在相同的条件下使用collection.find({condition}).cursor(),并在单独的for loop 中对doc 进行迭代,但我知道(实际上是一位朋友告诉我)MongoDB 可以通过@ 做同样的事情987654335@ 阶段通过$cond (if/else) 块。

其实我猜在那种情况下//Result之后的下一个$operator应该是$group阶段,像这样:

            {
                $group: {
                    _id: "$lastModified",
                    quantity: {$sum: {$cond: if/else }" $quantity"},
                    if (below 100) {$sum: "$value" }
                }
            }

但我不知道该怎么做。那么任何人都可以给我一个例子吗? 或者aggregatestage和.find({}).cursor和手动迭代没有区别?

【问题讨论】:

  • 我建议使用聚合查询,首先根据 if/else 条件进行过滤,然后应用累加器
  • 你可以做的另一件事是应用一个reduce函数docs.mongodb.com/manual/core/map-reduce/index.html
  • $filter 将是 if/else 条件,然后应用 $sum,如果您需要对未进入 if 条件的文档执行此操作,您可以使用 $facet 根据条件进行分组
  • 使用mapreduce时要注意内存,查询和聚合总是更快
  • map-reduce 将在获取集合后在内存中运行我认为如果您将索引放入集合中不会提高性能,请进行聚合,稍后您会感谢我的 ;)

标签: javascript mongodb mongoose aggregation-framework


【解决方案1】:

实际上我通过find({query}).cursor() 语法解决了我的问题并推送到数组,例如:

        let market_quantity = await auctions_db.find({query}).cursor();
        for (let order = await market_quantity.next(); order != null; order = await market_quantity.next()) {
            if (quantity < arg_quantity) {
                quantity += order.quantity;
                price_array.push(order.price);
                value += order.buyout;
            } else {
                break;
            }
        }

【讨论】:

    猜你喜欢
    • 2019-03-05
    • 2019-02-25
    • 2018-01-05
    • 2016-12-25
    • 1970-01-01
    • 2011-01-08
    • 2022-12-01
    • 1970-01-01
    相关资源
    最近更新 更多