Getting first day of week from week number in mongodb

前端 未结 3 1172
暗喜
暗喜 2021-01-13 14:59

I have collection containing date field. I\'m Grouping records by week and other related fields.

This is my aggregation query:



        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 15:35

    For mongo >= v3.4, look at weekStart. The idea is to substruct milliseconds from given Timestamp

    db.raw.aggregate([
             // stage 1
            { "$match" : {
                "Timestamp":{
                    "$gte": ISODate("2012-05-30"), 
                    "$lt": ISODate("2014-07-31")
                }
            }},
    
             // stage 2
            { "$project" : {
    
               ApplicationId: 1,
               Country: 1,
               week: {$isoWeek: "$Timestamp"},
    
               // [TRICK IS HERE] Timestamp - dayOfWeek * msInOneDay
               weekStart: { $dateToString: { format: "%Y-%m-%d", date: { // convert date
                 $subtract: ["$Timestamp", {$multiply: [ {$subtract:[{$isoDayOfWeek: "$Timestamp"},1]}, 86400000]}] 
               }}},
    
             // stage 3
            { "$group" : {
            "_id":{ 
                "ApplicationId": "$ApplicationId",
                "Country": "$Country",
                "week": "$week"
            },
            "Date":{ "$first": "$weekStart" },
            "Visits": { "$sum": 1 }
            }}        
     ])
    

提交回复
热议问题