0

I have a doc in my mongodb that looks like this -

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

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.

I believe I have to the aggregation framework, but I can't figure out how to get the results I need. Thanks.

1 Answer 1

2

In the 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?):

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

Can you translate this to the Java api? or i'll try to add that too.

... ok, here's some Java:

Assuming the docs in my collection are {_id : "someid", name: "somename", value: "some value"} then this code shows them grouped by name:

 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. You can then add the rest of the fields once you get this query working.

Sign up to request clarification or add additional context in comments.

2 Comments

Any help with the conversation to Java would be appreciated.
@bickster Your wish is my command. I just completed the mongouniversity m101j course, so I need the practise to get it stuck in my mind : )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.