Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select distinct rows from MongoDB

How do you select distinct records in MongoDB? This is a pretty basic db functionality I believe but I can't seem to find this anywhere else.

Suppose I have a table as follows

--------------------------
| Name    | Age          |
--------------------------
|John     | 12           |
|Ben      | 14           |
|Robert   | 14           |
|Ron      | 12           |
--------------------------

I would like to run something like SELECT DISTINCT age FROM names WHERE 1;

like image 362
Josh K Avatar asked Jun 22 '10 15:06

Josh K


2 Answers

db.names.distinct('age')

like image 82
Andrey Avatar answered Oct 14 '22 13:10

Andrey


Looks like there is a SQL mapping chart that I overlooked earlier.

Now is a good time to say that using a distinct selection isn't the best way to go around querying things. Either cache the list in another collection or keep your data set small.

like image 43
Josh K Avatar answered Oct 14 '22 11:10

Josh K