Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
APPLIES TO:
MongoDB vCore
The distinct
command is used to find the unique values for a specified field across a single collection. This command is useful when you need to identify the set of distinct values for a field without retrieving all the documents or when you need to perform operations like filtering or grouping based on unique values.
The basic syntax of the distinct
command is as follows:
db.collection.distinct(field, query, options)
field
: The field that receives the returned distinct values.query
: Optional. A query that specifies the documents from which to retrieve the distinct values.options
: Optional. Other options for the command.
Here are examples using the provided sample JSON structure.
To find the distinct categoryName
in the salesByCategory
array:
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
]
To find the distinct eventName
in the promotionEvents
array:
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 }
]
}
]
To find the distinct discountPercentage
in the discounts
array for the "Summer Sale" event:
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 options for Migrating from MongoDB to Azure Cosmos DB for MongoDB (vCore)
- Read more about Feature compatibility with MongoDB