Is there an effective way of getting the first document from a query? Typically this would be using FirstOrDefault() with LINQ collects or a TOP in SQL.
Say the collection looks something like this:
{
name: "John",
position: 3
},
{
name: "Mary",
position: 1
},
{
name: "Peter",
position: 2
}
I need to retrieve only the single document with the highest value position. I.e. the "Mary" document in this case.
Using the C# SDK, I would have to perform something like this:
Client.CreateDocumentQuery<T>(Collection.DocumentsLink)
.Where(somethingOtherCriteria);
.OrderByDescending(x => x.Position)
.AsEnumerable()
.FirstOrDefault());
This will retrieve ALL the documents in the collection (after applying the relevant filter) and then fetching the first from the list. This could still bring in thousands of irrelevant documents over the wire.
Is it not possible to execute FirstOrDefault() on the server?
One option is to set the max response size to 1, and grab only the first page from the query iterator:
var query = client.CreateDocumentQuery<Family>(collectionLink, "SELECT * FROM myCollection", new FeedOptions { MaxItemCount = 1 }).AsDocumentQuery();
var feedResponse = await query.ExecuteNextAsync<Family>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With