# 집계 프레임워크 (Aggregation Framework)

문법은 MongoShell과 똑같지만 다시 한번 remind한다는 생각으로 작성해 보았다.

```
db.collection.aggregate(pipeline, options)
```

* Example

```
mydb.mycollection.aggregate([
{‘$match’ : {‘$text’ : {‘$search’ : ‘ value ’}}},
{‘$sort’ : SON([(‘ field ’, 1)])}, # from bson.son import SON
{‘$project’ : {‘ field1 ’ : 1, ‘ field2 ’ : 1, ‘ field3 ’ : 0}}
])
```

{% hint style="warning" %}
Python의 Dictionary는 순서가 없이 저장된다. 평소에는 별 문제가 없을 수도 있으나, sorting과 같이 먼저 정렬이 되어야 하는 key와 나중에 정렬이 되는 key를 선택할 시에는 문제가 된다. 아래의 링크를 타고 BSON에 대해 더 자세히 알아보자.
{% endhint %}

{% content-ref url="../appendix/bson" %}
[bson](https://koonkim.gitbook.io/mongodb/appendix/bson)
{% endcontent-ref %}

{% hint style="info" %}
index를 사용하는것은 pipeline상 무조건 앞에 쓰는 것이 좋다.

pipeline상 뒤에 있게 되면 index를 사용하지 못하게 될 수 있으니, 질의를 수행하지 못하게 될수도 있어서 에러를 내뱉을 수 있다.&#x20;

&#x20;`4.0버전에서는 geospatial과 text query는 무조건 맨 앞 stage에 작성해야 한다.`
{% endhint %}

### GeoNear

* only use $geoNear as the first stage of a pipeline.

```
mydb.mycollection.aggregate([{
‘$geoNear’ : {
‘near’ : { type: ‘ value ’, ‘coordinates’: [ longtitude , latitude ] },
‘distanceField’ : ‘ stringvalue ’,
‘query: {key:value},
‘maxDistance’ : value
}}])
```
