你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

distinct

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

Syntax

命令的基本语法 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:查找特定事件的不同折扣百分比

若要查找“夏季销售”事件的数组中的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
]