【问题标题】:MongoDB conditional aggregateMongoDB条件聚合
【发布时间】:2015-06-03 04:17:52
【问题描述】:

我有收藏,在里面我必须根据条件计算价格,如果对于选定的日期(即从 2015 年 1 月 20 日到 2015 年 1 月 22 日,3 人)有不同的定价,如果没有然后添加一个pricing.basic 值加上如果人数多于personIncluded 我需要乘以。

样本收集:

{
    "_id" : ObjectId("5473572cf1a76349020041c6"),
    "calendar" : [ 
        {
            "date" : ISODate("2015-01-20T12:41:20.000Z"),
            "status" : true
        }, 
        {
            "date" : ISODate("2015-01-21T12:41:20.000Z"),
            "status" : true,
            "pricing": {
                "basic": 9900,
                "perPerson": 1100
            }
        }, 
        {
            "date" : ISODate("2015-01-22T12:41:20.000Z"),
            "status" : true
        }, 
        {
            "date" : ISODate("2015-01-23T12:41:20.000Z"),
            "status" : false
        }, 
        {
            "date" : ISODate("2015-01-24T12:41:20.000Z"),
            "status" : false
        }, 
        {
            "date" : ISODate("2015-01-25T12:41:20.000Z"),
            "status" : false
        }
    ],
    "pricing" : {
        "basic" : 9470,
        "currency" : "USD",
        "personsIncluded" : 2,
        "perPerson" : 1000
    }
}

我在寻找什么:

(
    if $calendar.date = currentSearchDate && $calendar.pricing
        $calendar.pricing + (($pricing.personsIncluded-personsInputValue) * ($calendar.perPerson ?: $pricing.perPerson))
    else
        ($pricing.basic + (($pricing.personsIncluded-personsInputValue) * $pricing.perPerson ))
) + (
    if $calendar.date = currentSearchDate2 && $calendar.pricing
        $calendar.pricing + (($pricing.personsIncluded-personsInputValue) * ($calendar.perPerson ?: $pricing.perPerson))
    else
        ($pricing.basic + (($pricing.personsIncluded-personsInputValue) * $pricing.perPerson ))
) + (
    if $calendar.date = currentSearchDate3 && $calendar.pricing
        $calendar.pricing + (($pricing.personsIncluded-personsInputValue) * ($calendar.perPerson ?: $pricing.perPerson))
    else
        ($pricing.basic + (($pricing.personsIncluded-personsInputValue) * $pricing.perPerson ))
) + ...

当然唯一的选择是聚合框架,但它可以做这样的事情吗,或者最好得到所有结果(当然过滤),将它们推入临时集合,然后排序和过滤。

【问题讨论】:

  • 你应该可以在聚合框架中使用$cond$add$multiply等运算符来完成。
  • 嗯,你能帮我解决这个问题吗——哪怕是一点点

标签: mongodb aggregation-framework


【解决方案1】:

看看那个帖子:

MongoDB conditional aggregation

我已经发布了条件聚合,条件过滤器仍然缺失。

这可能会对您有所帮助。 如果您仍然需要帮助来构建聚合,请告诉我,我会尽力帮助您。

【讨论】:

  • 在我的例子中用你的价格替换 true 和 false。
猜你喜欢
  • 2014-06-08
  • 2019-03-05
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 2021-11-04
  • 2012-11-30
  • 2018-09-16
相关资源
最近更新 更多