0

Let collection be

[
    {area:'121',name:'r',age:'1'},
    {area:'122',name:'rt',age:'21'},
    {area:'121',name:'r',age:'1'}

]

I want query that will return

[
    {area:'121',name:'r',age:'1'},
    {area:'122',name:'rt',age:'21'}     
]

i.e entry that have unique area value. I tried to search and use distinct

collections.collection('collection')
                        .distinct('area', (err, sus) => {
                            if (err) {
                                console.log(err)
                                resp.status(501).send()
                            } else {
                                console.log(sus)
                                resp.send(sus)
                            }
                        })

but the output is

["121","122"]

This is giving me only distinct values but i want the full entry. How to get that?

chridam
  • 100,957
  • 23
  • 236
  • 235
Rajan Lagah
  • 2,373
  • 1
  • 24
  • 40
  • You can use the aggregate operation to get unique values, i guess. Check this answer https://stackoverflow.com/questions/20655506/get-distinct-records-values/44887521#44887521 – Shyam Babu Oct 24 '18 at 09:02
  • As specified in one of the duplicates, you need to run an aggregation pipeline like `collections.collection('collection').aggregate([ { "$group": { "_id": "$area", "name": { "$first": "$name" }, "age": { "$first": "$age" } } }, { "$project": { "_id": 0, "area": "$_id", "name": 1, "age": 1 } } ], (err, sus) => { if (err) { console.log(err) resp.status(501).send() } else { console.log(sus) resp.send(sus) } })` – chridam Oct 24 '18 at 10:25

0 Answers0