Reputation: 3755
I'm trying to get a list of distinct elements as my final result in a MongoTemplate aggregate function. And I'm receiving a list like below at the middle of the aggregate,
[
{
"_id":"333",
"name":"cat Three name",
"description":"cat item description"
},
{
"_id":"222",
"name":"cat Two name",
"description":"cat item description"
},
{
"_id":"222",
"name":"cat Two name",
"description":"cat item description"
},
{
"_id":"333",
"name":"cat Three name",
"description":"cat item description"
}
]
How can I add another AggregationOperation to get distinct values as my final result like below?
[
{
"_id":"222",
"name":"cat Two name",
"description":"cat item description"
},
{
"_id":"333",
"name":"cat Three name",
"description":"cat item description"
}
]
Upvotes: 1
Views: 1094
Reputation: 13103
Add two steps:
db.collection.aggregate([
{
$group: {
_id: "$_id",
data: {
$first: "$$ROOT"
}
}
},
{
$replaceRoot: {
newRoot: "$data"
}
}
])
Aggregation agg = newAggregation(
... // Your pipeline
group("_id").first("$$ROOT").as("data"),
replaceRoot("data")
);
Upvotes: 3