distinct

适用对象: MongoDB vCore

distinct 命令用于在单个集合中查找指定字段的唯一值。 当您需要识别字段的非重复值集而不想检索所有文档时,或者当您需要根据唯一值执行筛选或分组等操作时,此命令非常有用。

语法

distinct 命令的基本语法如下:

db.collection.distinct(field, query, options)
  • field:接收返回的非重复值的字段。
  • query:可选。 指定要从中检索非重复值的文档的查询。
  • options:可选。 该命令的其他选项。

示例

以下是使用提供的示例 JSON 结构的示例。

示例 1:查找销售中的非重复类别

若要在数组 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
]  

示例 2:在促销活动中查找非重复活动名称

若要在数组 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 }
    ]
    }
]

示例 3:查找特定活动的不同折扣百分比

在“夏季销售”活动的 discountPercentage 数组中查找非重复 discounts

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
]