How to aggregate by floor in MongoDB

后端 未结 1 343
天命终不由人
天命终不由人 2020-12-12 00:04

MongoDB Aggregation Framework doesn\'t have floor function. It only has simple arithmetic operators. So, how to compose floor function using them?<

相关标签:
1条回答
  • 2020-12-12 00:25

    According to definition floor(number) = number - (number % step) we can compose our aggregation formula:

    {$subtract: ["$number", {$mod: ["$number", <step>]}]}
    

    where step is order of magnitude. First, it computes remainder with $mod and then it computes difference with $subtract.

    So, grouping Users by age floored to whole numbers will be

    db.users.aggregate(
        {$group: {_id: {$subtract: ["$age", {$mod: ["$age", 1]}] }}} )
    

    If you want to floor to 10s or 1000s use 10 or 1000 instead of 1.

    0 讨论(0)
提交回复
热议问题