aman
aman

Reputation: 375

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

Upvotes: 8

Views: 4384

Answers (2)

Mool Shankar Mishra
Mool Shankar Mishra

Reputation: 1

For Java code:

    Bson field1 = new Document("team_code", "$team_code").append("team_id", "$team_id");Bson groupField = new Document("_id", field1 );
    Bson group = new Document("$group", groupField );List<Bson> bsonList = new ArrayList<Bson>(); 
    bsonList.add(group);    
    com.mongodb.client.AggregateIterable<Document> res=collection.aggregate( bsonList );
      for (Document doc : res) {
         Document subDoc=(Document)doc.get("_id");
         System.out.println(subDoc.get("team_code")+" : "+subDoc.get("team_id"));
        //deptEnvs.put(subDoc.getInteger("dept"), subDoc.getString("smEnv"));  

         }

Upvotes: 0

robjwilkins
robjwilkins

Reputation: 5652

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.

Upvotes: 11

Related Questions