'mongodb get all unique values for each unique field
I am looking to query a collection of property prices on mongodb. I would like to return the unique prices only.
There are multiple entries for each property, but I want to return only the unique prices associated with the propertyID.
How would I structure the query to remove the duplicate values of price for each propertyID?
In the table below, there are 5 entries for the price of 400,000, and one for 425,000, for propertyID 752276. I would like to return just the two unique prices, but for all entries in the collection.
To further explain what I am looking for,
If I had the object bellow, I would only want to return a:{10,20,30},b:{10,20}
a:{10,20,10,30}
b:{10,20,20,20}
Solution 1:[1]
You can achieve this with simple aggregation pipelines
{
$group:{
"_id": "$propertyID", //Group by property ID,
"uniquePrices" : {
"$addToSet" : "$price" //It will give you propertyID wise unique prices
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gibbs |

