Get distinct records values

Solution 1:

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

> db.test.distinct("name")
[ "my_name", "john" ]

Solution 2:

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

Solution 3:

db.test.aggregate([{$group: {_id: "$name", salary: {$max: "$salary"}}}])

should list all names with their salaries.

$max returns the highest salary per element. You could also choose $first etc, see https://docs.mongodb.com/manual/reference/operator/aggregation/group/#accumulator-operator.

Solution 4:

If you don't care about the content of varying fields but want the whole records, this will keep the (whole, thanks to $$ROOT) first document found for each "name" :

db.coll.aggregate([
  { "$group": { 
    "_id": "$name", 
    "doc": { "$first": "$$ROOT" }
  }},
  { "$replaceRoot": {
    "newRoot": "$doc"
  }}
])

$replaceRoot will serve them as documents instead of encapsulating them in a doc field with _id.

If you are concerned about the content of the varying fields, I guess you may want to sort the documents first :

db.coll.aggregate([
  { "$sort": { "$salary": 1 }},
  { "$group": { 
    "_id": "$name", 
    "doc": { "$first": "$$ROOT" } 
  }},
  { "$replaceRoot": {
    "newRoot": "$doc"
  }}
])