此 distinct 指令用於尋找單一集合中指定欄位的唯一值。 此指令在您需要識別欄位的不同值集合而不需取得所有文件,或需要根據唯一值進行篩選或分組等操作時非常有用。
語法
指令 distinct 的基本語法如下:
db.collection.distinct(field, query, options)
-
field: 接收回傳不同值的欄位。 -
query:隨意的。 一個查詢,指定要從哪些文件中取得不同值。 -
options:隨意的。 指揮的其他選項。
範例
以下是使用範例 JSON 結構的範例。
範例一:在銷售中尋找不同的類別
要在陣salesByCategory列中找到不同的 categoryName :
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
]
範例二:在促銷活動中找到不同的活動名稱
要在陣promotionEvents列中找到不同的 eventName :
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 }
]
}
]
範例三:尋找特定活動的不同折扣百分比
要在「夏季特賣」活動的名單中找到特別discountPercentagediscounts款項:
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
]
相關內容
- Review Migrating from MongoDB to Azure DocumentDB 的選項
- 閱讀更多關於 MongoDB 功能相容性的資訊