Search code examples
c#linqazure-cosmosdb

Azure CosmosDB: Read exactly one document via Microsoft.Azure.DocumentDb API


I am querying DocumentDB using LINQ and want to read only one document e.g. FirstOrDefault. What's the right way to do that? Here's the code that may give me multiple documents. How should I modify it so that it reads only the first document?

dynamic doc = from f in client.CreateDocumentQuery(collection.DocumentsLink)
              where f.Id == userId.ToString()
              select f;

Solution

  • Just apply FirstOrDefault on your result:-

    dynamic doc = (from f in client.CreateDocumentQuery(collection.DocumentsLink)
                  where f.Id == userId.ToString()
                  select f).FirstOrDefault();