0

이것은 question과 관련됩니다.날짜/요일별/일별 그룹

이는 내 데이터가 설정됩니다

[ 
    { 
    "rating": 4, 
    "ceatedAt": ISODate("2016-08-08T15:32:41.262+0000") 
    }, 
    { 
    "rating": 3, 
    "createdAt": ISODate("2016-08-08T15:32:41.262+0000") 
    }, 
    { 
    "rating": 3, 
    "ceatedAt": ISODate("2016-07-01T15:32:41.262+0000") 
    }, 
    { 
    "rating": 5, 
    "createdAt": ISODate("2016-07-01T15:32:41.262+0000") 
    } 
] 

내가 날짜 범위에 주 또는 월 단위로 기초를 필터링 할 수 있어야합니다.

몽고에서 어떻게 작성합니까?

일별 그룹화에 대한 답변입니다.

db.collection.aggregate([ 
    { 
     "$project": { 
      "createdAtWeek": { "$week": "$createdAt" }, 
      "createdAtMonth": { "$month": "$createdAt" }, 
      "rating": 1 
     } 
    }, 
    { 
     "$group": { 
      "_id": "$createdAtWeek", 
      "average": { "$avg": "$rating" }, 
      "month": { "$first": "$createdAtMonth" } 
     } 
    } 
]) 

및 월별 집계를위한

, 생성 된 사용하는 $group 키를 교환 : 주 단위로 그룹화

db.collection.aggregate([ 
    { 
     "$project": { 
      "formattedDate": { 
       "$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" } 
      }, 
      "createdAtMonth": { "$month": "$ceatedAt" }, 
      "rating": 1 
     } 
    }, 
    { 
     "$group": { 
      "_id": "$formattedDate", 
      "average": { "$avg": "$rating" }, 
      "month": { "$first": "$createdAtMonth" }, 
     } 
    } 
]) 

답변

1

는 주로 날짜 부분을 추출하는 Date Aggregation Operators를 사용하는 다음 파이프 라인을 실행 월 필드 :

db.collection.aggregate([ 
    { 
     "$project": { 
      "createdAtWeek": { "$week": "$createdAt" }, 
      "createdAtMonth": { "$month": "$createdAt" }, 
      "rating": 1 
     } 
    }, 
    { 
     "$group": { 
      "_id": "$createdAtMonth", 
      "average": { "$avg": "$rating" }, 
      "week": { "$first": "$createdAtWeek" } 
     } 
    } 
])