Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a distinct set of fields in MongoDB

I have the following JSON collection in MongoDB.

{
    "_id": ObjectId("57529381551673386c9150a6"),
    "team_code": 3,
    "team_id": 2
},
{
     "_id": ObjectId("57529381551673386c91514a"),
     "team_code": 4,
     "team_id": 5
},
{
   "_id": ObjectId("57529381551673386c91514b"),
   "team_code": 3,
   "team_id": 2
},
{
   "_id": ObjectId("57529381551673386c91514c"),
   "team_code": 4,
   "team_id": 5,
}

As it can be seen from the data , there a 2 records each with (team_code=3, team_id =2) and (team_code =4, team_id=5). Is it possible to get the distinct set of team codes and team ids. Some thing like ,

{
 "team_code" : 3, "team_id" : 2
},
{
 "team_code" : 4, "team_id" : 5,
}
like image 496
aman Avatar asked Jun 09 '16 10:06

aman


People also ask

How do I get unique fields in MongoDB?

In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.

Can we use find and distinct together in MongoDB?

Both the find and distinct operations are very useful when it comes to retrieving data from MongoDB. The find operation returns the data all at once or according to the query and projection. The distinct operation has a special functionality of retrieving unique values of a specified field.

What does distinct do in MongoDB?

distinct() considers each element of the array as a separate value. For instance, if a field has as its value [ 1, [1], 1 ] , then db. collection. distinct() considers 1 , [1] , and 1 as separate values.

How do I display a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


1 Answers

You can do this using the following Aggregation Pipeline:

var distinctIdCode = { $group: { _id: { team_code: "$team_code", team_id: "$team_id" } } }
db.foo.aggregate([distinctIdCode])

This will give you:

{ "_id" : { "team_code" : 4, "team_id" : 5 } }
{ "_id" : { "team_code" : 3, "team_id" : 2 } }

This query returns new documents created from the documents in your collection. The documents returned have an _id which is the result of grouping the collection documents on the team_code and team_id fields.

like image 76
robjwilkins Avatar answered Oct 13 '22 23:10

robjwilkins