此 distinct 指令用於尋找單一集合中指定欄位的唯一值。 此指令在您需要識別欄位的不同值集合而不需取得所有文件,或需要根據唯一值進行篩選或分組等操作時非常有用。
語法
指令 distinct 的基本語法如下:
db.collection.distinct(field, query, options)
-
field: 接收回傳不同值的欄位。 -
query:選擇性。 一個查詢,指定要從哪些文件中取得不同值。 -
options:選擇性。 指揮的其他選項。
範例
以下是使用範例 JSON 結構的範例。
範例一:在銷售中尋找不同的類別
要在陣categoryName列中找到不同的 salesByCategory :
db.stores.distinct("sales.salesByCategory.categoryName")
範例輸出
[
"Music Theory Books",
"Superfoods",
"Harmonicas",
"Garden Tools"
]
範例二:在促銷活動中找到不同的活動名稱
要在陣eventName列中找到不同的 promotionEvents :
db.stores.distinct("promotionEvents.eventName")
範例輸出
[
"Super Saver Celebration",
"Incredible Discount Days"
]
範例三:尋找特定活動的不同折扣百分比
要在「夏季特賣」活動的名單中找到特別discountPercentagediscounts款項:
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
]