라이브러리

[PHP] CollectionFind::sort - 정렬 기준 설정




CollectionFind::sort


CollectionFind::sort는 MongoDB의 CollectionFind 메소드에서 사용할 수 있는 옵션 중 하나입니다. 이 옵션을 사용하면 MongoDB에서 데이터를 조회할 때 결과를 정렬할 수 있습니다.

# 사용법


CollectionFind::sort 옵션을 사용하려면, 다음의 형식으로 사용할 수 있습니다.

#hostingforum.kr
php

$collection = (new MongoDBClient)->test->mycollection;

$cursor = $collection->find()->sort([ '필드명' => 1 ]); // 오름차순

$cursor = $collection->find()->sort([ '필드명' => -1 ]); // 내림차순



# 예제


다음 예제는 MongoDB의 test.mycollection 컬렉션에서 이름 필드를 오름차순으로 정렬한 결과를 조회하는 예제입니다.

#hostingforum.kr
php

$collection = (new MongoDBClient)->test->mycollection;

$cursor = $collection->find()->sort([ 'name' => 1 ]);



foreach ($cursor as $document) {

    echo $document['name'] . "
";

}



# 옵션


CollectionFind::sort 옵션에는 여러 옵션이 있습니다.

- `1` : 오름차순 정렬
- `-1` : 내림차순 정렬
- `array` : 여러 필드를 정렬할 때 사용

예를 들어, 다음 예제는 MongoDB의 test.mycollection 컬렉션에서 이름 필드를 오름차순으로, 나이 필드를 내림차순으로 정렬한 결과를 조회하는 예제입니다.

#hostingforum.kr
php

$collection = (new MongoDBClient)->test->mycollection;

$cursor = $collection->find()->sort([

    'name' => 1,

    'age' => -1

]);



foreach ($cursor as $document) {

    echo $document['name'] . " " . $document['age'] . "
";

}



# 참고


CollectionFind::sort 옵션은 MongoDB의 CollectionFind 메소드에서 사용할 수 있는 옵션 중 하나입니다. 이 옵션을 사용하면 MongoDB에서 데이터를 조회할 때 결과를 정렬할 수 있습니다. 또한, 여러 필드를 정렬할 때 사용할 수 있습니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 651 페이지

검색

게시물 검색