Finding a Single Field Set 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 you can see from the data, there are 2 entries, each with ( team_code=3, team_id =2) and ( team_code =4, team_id=5). Is it possible to get a clear set of command codes and command identifiers. Some things like,

{
 "team_code" : 3, "team_id" : 2,
 "team_code" : 4, "team_id" : 5,
}
+4
source share
1 answer

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 documents in your collection. The returned documents have _id, which is the result of grouping the collection documents in the team_codeand fields team_id.

+5
source

All Articles