1

What would be the corresponding mongo query for below SQL that gets the lat and long of the most recent doc for each did:

Query : what is the last location for all devices

did  : device id
ts   : time stamp
lat  : latitude 
long : longitude 

SQL Query

  SELECT 
        did , ts, `lat`, `long`
    FROM
        points
            JOIN
        (SELECT 
            MAX(ts) AS maxTs, did
        FROM
            points
        GROUP BY did) MxData ON points.ts = MxData.maxTs
            AND MxData.did = points.did;

Below is the Mongo Query, I am able to get max time stamp for device but not sure how to print the corresponding lat and long

db.points.aggregate( [{ $group:{_id: "$did", maxTs: { $max: "$ts" }}}]).pretty();
2
  • Your schema is normalized I think while it should not be in case of mongo. Commented Apr 11, 2017 at 6:55
  • Everything is in one document it is not normalized Commented Apr 11, 2017 at 10:39

1 Answer 1

1

I found the solution , the query is

db.points.aggregate([
    {$sort:{"ts":1}} , 
    {$group:{"_id":"$did" , result:{$last:"$ts"}  , lat:{$last:"$lat"} , lon:{$last:"$lon"}}}
    ]);
Sign up to request clarification or add additional context in comments.

Comments

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.