83

I have a collection of documents :

{
    "networkID": "myNetwork1",
    "pointID": "point001",
    "param": "param1"
}
{
    "networkID": "myNetwork2",
    "pointID": "point002",
    "param": "param2"
}
{
    "networkID": "myNetwork1",
    "pointID": "point003",
    "param": "param3"
}
...

pointIDs are unique but networkIDs are not.

Is it possible to query Mongodb in such a way that the result will be : [myNetwork1,myNetwork2]

right now I only managed to return [myNetwork1,myNetwork2,myNetwork1]

I need a list of unique networkIDs to populate an autocomplete select2 component. As I may have up to 50K documents I would prefer mongoDb to filter the results at the query level.

serv-inc
  • 35,772
  • 9
  • 166
  • 188
Franckl
  • 1,401
  • 2
  • 12
  • 17

1 Answers1

193

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

db.collection.distinct('NetworkID')

Dylan
  • 2,161
  • 2
  • 27
  • 51
Laura Uzcategui
  • 2,062
  • 1
  • 11
  • 6
  • 43
    What if I want to get full record? This will only return `NetworkID`. – Half Blood Prince Aug 01 '16 at 04:48
  • 10
    @HalfBloodPrince, what full record? `distinct` returns all the unique values for a field. Returning a record or records doesn't make sense in this context. You'll have to use the aggregation pipeline [`$group` operator](https://docs.mongodb.com/manual/reference/operator/aggregation/group/) for distinct + records. – Paul Nov 03 '16 at 14:05
  • 8
    @HalfBloodPrince: if you want a full record, have a look at https://stackoverflow.com/a/44887521/1587329 – serv-inc Jul 03 '17 at 14:01
  • @HalfBloodPrince For full records you want to use an aggregation with `$$ROOT`, see [here](https://stackoverflow.com/a/59756228/812102). – Skippy le Grand Gourou Jan 15 '20 at 17:00
  • You put the signature of the method `distinct`, but I would like to know about the second parameter, for an example, how can I distinct by id and get this data until a date? Like I have a property called PaymentDate in this table. – Vagner Wentz Oct 18 '22 at 12:06