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,
}
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.
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.
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.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With