Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb find() query : return only unique values (no duplicates) [duplicate]

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.

like image 374
Franckl Avatar asked Jan 26 '15 17:01

Franckl


People also ask

How do I query unique values in MongoDB?

To get unique values and ignore duplicates, use distinct() in MongoDB. The distinct() finds the distinct values for a specified field across a single collection and returns the results in an array.

How does MongoDB store unique data?

MongoDB's Unique Constraint makes certain that the fields indexed in it, do not store duplicate values for the same field, i.e., making sure the uniqueness of fields. By default, MongoDB enforces this unique constraint on the “_id” field, while inserting new data.

What does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.


1 Answers

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')

like image 168
Laura Uzcategui Avatar answered Sep 25 '22 13:09

Laura Uzcategui