> For the complete documentation index, see [llms.txt](https://koonkim.gitbook.io/mongodb/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://koonkim.gitbook.io/mongodb/master/aggregate-framework/untitled-1/basic.md).

# Basic

## 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 }}])
  ```
