如何聚合MongoDB中对象数组中的值

时间:2017-01-19 18:27:03

标签: mongodb mongodb-query aggregation-framework mongo-java mongo-java-driver

我存储汽车的文件,并希望将所有梅赛德斯汽车的温度作为一个数组,查询应该如何在Mongodb?

 { "_id" : { "$oid" : "5880ff305d15f416c89457b7" },
     "car" : "mercedes",
      "engine" : { 
            "sensor" : {
                        "temperatur" : "20",
                        "speed" : "100", 
                        "hue" : "40" 
                        }
                },
         "motor" : {
                    "Power" : "155", 
                    "Topspeed" : "400" 
                    } 
}

{ "_id" : { "$oid" : "5880ff305d15f416c89457b7" },
     "car" : "mercedes",
      "engine" : { 
            "sensor" : {
                        "temperatur" : "50",
                        "speed" : "100", 
                        "hue" : "40" 
                        }
                },
         "motor" : {
                    "Power" : "155", 
                    "Topspeed" : "400" 
                    } 
}

我想选择所有梅赛德斯汽车的温度并接收它。 结果应该像[20,50]

编辑: 我的代码看起来像下面的iam使用JAVA:

  MongoClient mongoClient = new MongoClient();
      MongoDatabase database = mongoClient.getDatabase("test");
      MongoCollection<Document> coll = database.getCollection("myTestCollection");

1 个答案:

答案 0 :(得分:1)

如果您对不同的值没有问题,可以尝试使用常规查询。

db.cars.distinct("engine.sensor.temperatur", {"car" : "mercedes"});

这会给你

[ "20", "50" ]

更新 - Java等价物:

List<String> temps = coll.distinct("engine.sensor.temperatur", new Document("car", "mercedes"), String.class).into(new ArrayList<>());

更新 - 聚合选项

Bson match = new Document("$match", new Document("car", "mercedes"));

Bson group = new Document("$group", new Document("_id", "$car").append("temps", new Document("$push", "$engine.sensor.temperatur")));

List<String> temps  = (List<String>) coll.aggregate(Arrays.asList(match, group)).map(document -> document.get("temps")).first();