Mongodb WeekofMonth? Mongodb WeekofMonth? mongodb mongodb

Mongodb WeekofMonth?


The $week operator gives you the week of year as described in the docs.

The week of month can be calculated by getting the day of month and dividing by 7.

db.activity.aggregate([    {$project: {        "year": {$year: "$createdAt"},        "month": {$month: "$createdAt"},        "weekOfMonth": {$floor: {$divide: [{$dayOfMonth: "$createdAt"}, 7]}}    }},    {$group: {        "_id": {"year": "$year", "month": "$month", "weekOfMonth": "$weekOfMonth"},        count: { $sum: 1 }    }},    {$match : { "_id.year" : 2016, "_id.month" : 5}}])

Note that the week of month here is 0 based. If you want it to start at 1 just $add 1. Also, the $floor operator is new in version 3.2.

Edit

You can simulate the floor using $mod (which exists in version 3.0)

"weekOfMonth": {$subtract: [{$divide: [{$dayOfMonth: "$createdAt"}, 7]}, {$mod: [{$divide: [{$dayOfMonth: "$createdAt"}, 7]}, 1]}]},