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

Aggregate Framework 에 대한 간단한 설명이 첨부되어야 함.

## 개념

![이런 느낌의 이미지가 들어가면 정말 좋을듯하네요](https://3918157821-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lb7Vg1sUEHzMkgFpUvH%2F-LdSWI9SVh5bj_mO2r5E%2F-LdSWKFbUunCHO2XrZbI%2Faggregation-pipeline.bakedsvg.svg?alt=media\&token=bb541155-dbbd-414d-aa70-e3814fe9e5e7)

위에 이미지를 1. $match, 2. group stage 이런식으로 하는것도 좋을 거 같네요&#x20;

## Aggregation Framework

* Syntax&#x20;

  ```python
  db.collection.aggregate(pipeline, options)
  ```
* Example

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

{% hint style="info" %}
MongoDB의 문서는 순서가 있지만 python의 dictionary에는 순서가 없다. &#x20;

평소에는 결과가 순서없이 나와도 무방할 수 있지만, MongoDB에 질의문에 dictionary가 포함될 경우에는 곤란해 질 수 있다.&#x20;

따라서, python에서 제공해 주는 아래의 library를 사용해야 한다.

```python
from bson.son import SON
"$sort": SON([("name", 1)])
```

{% endhint %}

## Aggregate with geoNear

아직 구현이 덜 된 건지 index를 활용을 못해서 그런지 몰라도 aggregation framework에서 공간 질의에 대해서는 아직 지원이  확실하진 않다.

GeoNear 질의는 일반 aggregate와 문법이 조금은 다르기 때문에 작성해 본다.

* only use $geoNearas the first stage of a pipeline

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