티스토리 뷰

728x90
반응형

 

 

만약 컬렉션에 아래와 같은 데이터가 들어있다고 가정했을 때,

{'regDate': ISODate("2021-03-01T00:00:00.121Z") , 'content': 'helloWorld!' },
{'regDate': ISODate("2021-03-01T12:24:41.121Z") , 'content': 'hello!' },
{'regDate': ISODate("2021-03-02T18:00:21.121Z") , 'content': 'World!' },
{'regDate': ISODate("2021-03-02T04:00:57.121Z") , 'content': 'hi~' },
{'regDate': ISODate("2021-03-02T11:29:38.121Z") , 'content': 'what?' },
{'regDate': ISODate("2021-03-03T15:07:22.121Z") , 'content': '^.^' },

 

 

1. 검색조건없이 컬렉션 안에 들어있는 모든 데이터를 날짜별로 카운팅하려면

> db.collection.aggregate([{"$project": { "formattedRegDate": { "$dateToString": {"format":"%Y-%m-%d", "date":"$registration_date"}} } }, {"$group":{"_id":"$formattedRegDate", "count":{"$sum":1}}}]);

> 결과

{'_id': '2021-03-01', 'count': 2},

{'_id': '2021-03-02', 'count': 3},

{'_id': '2021-03-03', 'count': 1}

 

날짜포맷에 %Y-%m-%d를 원하는 포맷으로 변경가능하고, count도 원하는 변수명으로 변경 가능하다.

 

 

 

2.  검색조건을 설정하여 조건에 부합하는 데이터만 가져와 날짜별로 카운팅하려면 {"$match"} 에 검색조건을 설정!

> db.collection.aggregate([ {"$match": {'content': {'$regex': 'World'} } } ,{"$project": { "formattedRegDate": { "$dateToString": {"format":"%Y-%m-%d", "date":"$registration_date"}} } }, {"$group":{"_id":"$formattedRegDate", "count":{"$sum":1}}}]);

> 결과

{'_id': '2021-03-01', 'count': 1},

{'_id': '2021-03-02', 'count': 1}

 

검색조건에 content에 'World'가 들어가는 데이터만 가져오도록 설정하였으므로 World가 들어간 데이터들만 카운팅된다.

 

 

 

728x90
반응형
댓글