【问题标题】:MongoDB equivalent to MySQL: select count(*) c, sum(if(x='A',1,0)) as a, sum(if(x='B',1,0)) as bMongoDB相当于MySQL:select count(*) c, sum(if(x='A',1,0)) as a, sum(if(x='B',1,0)) as b
【发布时间】:2019-12-14 06:01:28
【问题描述】:

我正在尝试编写一个行为类似于以下 SQL 查询的 MongoDB 聚合查询:

select foo
      , count(*) c
      , sum(if(x='A',1,0)) as a
      , sum(if(x='B',1,0)) as b
 from bar
group by foo
order by c desc

除了sum(if()) 部分,我什么都能做

  { '$group' :
    {
      _id :
      {
        foo : '$foo',
      },
      count : { '$sum' : 1 },
    }
    { '$sort' : { count : -1 } },
}

我缺少什么运算符来进行条件和?

【问题讨论】:

    标签: sql mongodb aggregation-framework


    【解决方案1】:

    $cond是你需要的运算符:

    { '$group' :
        { _id : { foo : '$foo' },
        count : { '$sum' : 1 },
        a: { '$sum': { '$cond': [ { '$eq': [ '$x', 'a' ] }, 1, 0 ] } },
        b: { '$sum': { '$cond': [ { '$eq': [ '$x', 'b' ] }, 1, 0 ] } },
        }        
    },
    { '$sort' : { count : -1 } },
    

    【讨论】:

    • 谢谢!如果你想要 2+ 个条件,例如sum(if(x='a' and y='b',1,0))
    • @DukeLeto 只需使用 $and 和双 $eq - 你基本上可以在那里放置任何条件,它不仅限于单个 $eq
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多