Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get distinct records values

Tags:

mongodb

Is there a way to query for objects with not same values on some field? For example I have Records:

{ id : 1, name : "my_name", salary : 1200 } { id : 2, name : "my_name", salary : 800 } { id : 3, name : "john", salary : 500 } 

Query : find all with NOT_THE_SAME(name)

I just want records with id 1 and 3 because I specified that I don't want records with same value in field name or 2 and 3, it does not matter in this situation.

like image 431
petomalina Avatar asked Dec 18 '13 10:12

petomalina


People also ask

How can I get distinct values from a table?

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

How do I get unique records in SQL?

The unique values are fetched when we use the distinct keyword. SELECT DISTINCT returns only distinct (different) values. DISTINCT eliminates duplicate records from the table. DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.

How can I get distinct values of all columns in SQL?

To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns.


2 Answers

You can use db.collection.distinct to get back an array of unique values:

> db.test.distinct("name") [ "my_name", "john" ] 
like image 82
Chris Seymour Avatar answered Sep 28 '22 22:09

Chris Seymour


You can also use a distinct sentence with filtered collection. For example, you can get distinct values of names from salaries over 800 with the following query:

db.test.distinct("name", { "salary": { $gt: 800 } }) 
like image 44
J.C. Gras Avatar answered Sep 28 '22 22:09

J.C. Gras