MongoDB 에서 어떻게 최소값(min)을 뽑아낼 수 있을까? (부제: MongoDB 문제 - Wind Direction 이 180 이상 360 이하 이면서, 가장 낮은 온도를 기록한 도시의 이름을 말하라.)

MongoDB 문제 : Wind Direction 이 180 이상 360 이하 이면서, 가장 낮은 온도를 기록한 도시의 이름을 말하라.

Reading clockwise from true north, the wind direction is measured by degrees around the compass up to 360 degrees. 

90 is East

180 is South

270 is West

360 is North

Your assignment is to figure out the "State" that recorded the lowest "Temperature" when the wind was coming from the west ("Wind Direction" between 180 and 360). Please enter the name of the state that meets this requirement. Do not include the surrounding quotes in providing your answer.


해결

1. 일단, Wind Direction이 180 이상 360 이하인 것을 find 한다.

db.data.find({'Wind Direction':{$gte:180,$lte:360}})

*
  $gte : equal + greater than
  $lte : equal + less than

2. sort로 온도를 기준으로 정렬한다.

* sort에 object로 Temperature를 넣고 value로는 1이나 -1을 준다.

1을 주면 작은 것부터 / -1을 주면 큰 것부터 정렬한다.

db.data.find({'Wind Direction':{$gte:180,$lte:360}}).sort({'Temperature':1})

3. 이렇게 되면 Wind Direction이 180이상 360이하이면서 온도가 가장 낮은 도시부터 쫙 정렬 될 것이다.

그러나, 우리가 원하는 것은 '180이상 360이하이면서 온도가 가장 낮은 도시의 이름' , 즉 하나만 알면 되므로 limit를 사용한다.

db.data.find({'Wind Direction':{$gte:180,$lte:360}}).sort({'Temperature':1}).limit(1);

* .limit(숫자) => 숫자만큼 document를 뽑아낸다.

즉, limit(1)을 하면 그 많은 문서들 중 딱 하나만 뽑아낸다.