简体   繁体   中英

How To: Get latest (newest) document from Cosmos DB?

I have a document database that has various properties including one named "SensorCaptureTime". I would like to retrieve only the newest document based on this property. So far, all I have figured out is how to retrieve all the documents sorted by SensorCaptureTime and then loop through them taking the last document in the list. Here's my current code:

            SensorData mostRecentSensorReadingDocument = null;

            // TODO: There has to be a better way to do this... just not sure what it is yet :-)
            var queryable = documentClient.CreateDocumentQuery<SensorData>(
                collectionUri,
                new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true })
                .OrderBy(b => b.SensorCaptureTime)
                .AsDocumentQuery();

            while (queryable.HasMoreResults)
            {
                foreach (SensorData sensorReadingsDocument in await queryable.ExecuteNextAsync<SensorData>())
                {
                    mostRecentSensorReadingDocument = sensorReadingsDocument;
                }
            }

            return mostRecentSensorReadingDocument;

I am assuming there is a way to request a single document, based on something like an aggregate function (eg Max), from a (Cosmos) document database without having to loop through the entire result set. Unfortunately, I haven't been able to find a working example.

Thanks!

Is there only one of these for the entire database or is there one for each device that has data written?

In either case, the problem with this approach is that over time the query will get increasingly more expensive and slow, especially if this is a cross partition query. A better approach may be to use Change Feed and update another collection that only contains a single record for every device that contains the latest reading. Whenever a new reading is inserted into Cosmos DB, Change Feed gets fired, you would then read change feed and do an Upsert on a second collection to update the relevant record with the latest reading. This way, each time you need that value it is simply a point-read which is super efficient.

Another option that may work is to use a composite index with the device id and SensorCaptureTime with Desc order and then do a Top 1 on the collection to get the last item inserted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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