Time series: How to get the most recent document?

@kevinadi Thank you so much for your detailed answer and the example!

I found a workaround that uses the internal collection you mentioned to get the most recent document without loading all other documents into memory. The first query finds the bucket that contains the most recent timestamp (which is fast because the index on control.max.timestamp is used), and the second query uses the timestamp to look up the document in the “virtual” time series collection:

async function findMostRecent() {
  const bucket = await db.collection("system.buckets.weather").findOne(
    {},
    {
      sort: { "control.max.timestamp": -1 },
      projection: { "control.max.timestamp": 1 }
    }
  );

  if (!bucket) return;

  return db.collection("weather").findOne({
    timestamp: bucket.control.max.timestamp
  });
}

Do you think this limitation could be mentioned in the documentation (here)? The introduction to time series collections says: “Time series collections behave like normal collections. You can insert and query your data as you normally would.” And the first query example on that page is a lookup of a single document, so I think it’s fair to assume that an index on the timestamp is used when sorting.

2 Likes