이 distinct 명령은 단일 컬렉션에서 지정된 필드에 대한 고유 값을 찾는 데 사용됩니다. 이 명령은 모든 문서를 검색하지 않고 필드에 대한 고유 값 집합을 식별해야 하거나 고유 값에 따라 필터링 또는 그룹화와 같은 작업을 수행해야 하는 경우에 유용합니다.
문법
명령의 기본 구문 distinct 은 다음과 같습니다.
db.collection.distinct(field, query, options)
-
field: 반환된 고유 값을 받는 필드입니다. -
query:선택적. 고유 값을 검색할 문서를 지정하는 쿼리입니다. -
options:선택적. 명령에 대한 기타 옵션입니다.
예시
다음은 제공된 샘플 JSON 구조를 사용하는 예제입니다.
예제 1: 판매에서 고유 범주 찾기
배열에서 고유 categoryName 항목을 찾으려면 다음을 수행 salesByCategory 합니다.
db.stores.distinct("sales.salesByCategory.categoryName")
샘플 출력
[mongos] StoreData> db.stores.distinct("sales.salesByCategory.categoryName")
[
{
_id: 'Discount Derby',
discounts: [
{ categoryName: 'Bath Sheets', discountPercentage: 25 },
{ categoryName: 'Tablecloths', discountPercentage: 25 },
{ categoryName: 'Drapes', discountPercentage: 25 }
]
}
]
[mongos] StoreData> db.stores.distinct("sales.salesByCategory.categoryName")
[
'Music Theory Books',
'Superfoods',
'Harmonicas',
'Garden Tools',
... 883 more items
]
예제 2: 승격 이벤트에서 고유 이벤트 이름 찾기
배열에서 고유 eventName 항목을 찾으려면 다음을 수행 promotionEvents 합니다.
db.stores.distinct("promotionEvents.eventName")
샘플 출력
[mongos] StoreData> db.stores.distinct("promotionEvents.eventName")
[
{
_id: 'Super Saver Celebration',
discounts: [
{ categoryName: 'Face Towels', discountPercentage: 25 },
{ categoryName: 'Printer Ribbons', discountPercentage: 25 },
{ categoryName: 'Chromebooks', discountPercentage: 25 }
]
}
]
예제 3: 특정 이벤트에 대한 고유 할인 비율 찾기
"Summer Sale" 이벤트의 배열에서 discounts 고유 discountPercentage 항목을 찾으려면 다음을 수행합니다.
db.stores.distinct("promotionEvents.discounts.discountPercentage", { "promotionEvents.eventName": "Incredible Discount Days" })
샘플 출력
[mongos] StoreData> db.stores.distinct("promotionEvents.discounts.discountPercentage", { "promotionEvents.eventName": "Incredible Discount Days" })
[
6, 17, 22, 25, 9, 15, 14,
7, 12, 19, 24, 5, 20, 10,
23, 16, 18, 21, 13, 11, 8
]
관련 콘텐츠
- MongoDB에서 Azure DocumentDB로 마이그레이션하기 위한 옵션 검토
- MongoDB와의 기능 호환성에 대해 자세히 알아보기