简体   繁体   English

MongoDB-分组依据-聚合-Java

[英]MongoDB - group by - aggregation - java

I have a doc in my mongodb that looks like this - 我的mongodb中有一个文档如下所示-

public class AppCheckInRequest {
    private String _id;
    private String uuid;
    private Date checkInDate;
    private Double lat;
    private Double lon;
    private Double altitude;
}
  • The database will contain multiple documents with the same uuid but different checkInDates 该数据库将包含多个具有相同uuid但checkInDates不同的文档

Problem 问题

I would like to run a mongo query using java that gives me one AppCheckInRequest doc(all fields) per uuid who's checkInDate is closest to the current time. 我想使用Java运行mongo查询,它为每个uuid的checkInDate最接近当前时间的用户提供一个AppCheckInRequest doc(所有字段)。

I believe I have to the aggregation framework, but I can't figure out how to get the results I need. 我相信我必须使用聚合框架,但是我无法弄清楚如何获得所需的结果。 Thanks. 谢谢。

In the mongo shell :- 在mongo shell中:-

This will give you the whole groupings: 这将为您提供整个分组:

db.items.aggregate({$group : {_id : "$uuid" , value : { $push : "$somevalue"}}} )

And using $first instead of $push will only put one from each (which is what you want i think?): 并且使用$ first代替$ push只会从每个$ push中放一个(这是我想要的吗?):

db.items.aggregate({$group : {_id : "$uuid" , value : { $first : "$somevalue"}}} )

Can you translate this to the Java api? 您可以将其翻译成Java api吗? or i'll try to add that too. 否则我也会尝试添加。

... ok, here's some Java: ...好的,这是一些Java:

Assuming the docs in my collection are {_id : "someid", name: "somename", value: "some value"} then this code shows them grouped by name: 假设我的收藏夹中的文档为{_id:“ someid”,名称:“ somename”,值:“ some value”},则此代码按名称将它们显示为分组:

 Mongo client = new Mongo("127.0.0.1");

    DBCollection col = client.getDB("ajs").getCollection("items");

    AggregationOutput agout = col.aggregate(
           new BasicDBObject("$group",
                   new BasicDBObject("_id", "$name").append("value", new BasicDBObject("$push", "$value"))));

    Iterator<DBObject> results = agout.results().iterator();


   while(results.hasNext()) {
     DBObject obj = results.next();

     System.out.println(obj.get("_id")+" "+obj.get("value"));

  }

and if you change $push to $first, you'll only get 1 per group. 如果将$ push更改为$ first,则每个组只会得到1。 You can then add the rest of the fields once you get this query working. 一旦此查询生效,您便可以添加其余字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM