Is there a way that I can get distinct results without duplicates based on one field?

let’s say I have these three documents, I want to get have results that have unique parentId.

 {name: "Jerk with rice", ingredients: {}, calories: 400, parentId: 234 }
  {name: "Jerk with rice", ingredients: {}, calories: 410, parentId: 234 }
  {name: "Jerk with rice", ingredients: {}, calories: 410, parentId: 200 }

I know that distinct method would give me result of - 234,200., However I want get the rest of the document, meaning that out of these 3 documents I want to retrieve only first and last.

1 Like

Hi @Lukas_Visinskis ,

Welcome to MongoDB Community.

The following aggregation will do it using $first operator in a $group:

[{$group : { "_id" : "$parentId" , doc : {$first : "$$ROOT"
}}}, {$replaceRoot : {newRoot : "$doc"}}]

Best regards,
Pavel

2 Likes

Welcome @Lukas_Visinskis !

Thanks for your help, just to add, would I be able to get same effect if I am using Atlas Search?

Yes just place the stages after the search stage.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.