Get distinct records values

Viewed 24972

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.

6 Answers

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

Mongo DB version > 3.4

db.test.distinct("name")

Mongo DB version < 3.4

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