在MongoDB中查找一组不同的字段

8

我在MongoDB中拥有以下JSON集合。

{
    "_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,
}

从数据中可以看出,有2条记录,每个记录具有 (team_code=3, team_id=2) 和 (team_code=4, team_id=5)。 是否可能获得不同的团队代码和团队ID集合。 类似于以下内容,

{
 "team_code" : 3, "team_id" : 2
},
{
 "team_code" : 4, "team_id" : 5,
}
2个回答

10

您可以使用以下聚合管道来实现此操作:

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

这将为您提供:

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

此查询返回从您的集合中创建的新文档。返回的文档具有一个 _id ,它是将集合文档按 team_codeteam_id 字段分组的结果。


为什么要使用“聚合管道”?这也可以通过find命令本身实现。请参见文档 - Shrabanee
1
使用聚合是因为结果需要基于team_code和team_id的唯一组合进行分组。这是聚合管道设计得很好的事情之一。 - robjwilkins
@robjwilkins 谢谢Rob。我在想如果我把这个放在一个变量里,比如说var temp,我该怎么访问这些字段呢? - aman

0
Java代码示例:
    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"));  

         }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接