Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DocumentDb: Get the first document

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?

like image 984
Dave New Avatar asked Nov 15 '25 12:11

Dave New


1 Answers

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>();
like image 164
Andrew Liu Avatar answered Nov 17 '25 07:11

Andrew Liu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!