How to read data from CosmosDb when i only have the partitionkey but not the id of the document

Viewed 45

When trying to read from CosmosDb i can select a document via:

  • Id Query
  • Id + PartitionKey Query

but how do i select data from CosmosDb when i only have the PartitionKey?

using Microsoft.Azure.Cosmos;
        
public class CosmosDbService : ICosmosDbService
{
    private Container _container;
    
    public CosmosDbService(
            CosmosClient cosmosDbClient,
            string databaseName,
            string containerName)
    {
        _container = cosmosDbClient.GetContainer(databaseName, containerName);
    }
    
    public async Task<Error> GetItemAsync(string partitionKey)
    {
        // selection only via partitionKey - does not work
        var response = await _container.ReadItemAsync<Error>(partitionKey, new PartitionKey(partitionKey));
        return response.Resource;

        // below one works as i am passing the Id (internally generated by CosmosDB)
        var id = "2e4e5727-86ff-4c67-84a6-184b4716d744";
        var response = await _container.ReadItemAsync<Error>(id, new PartitionKey(partitionKey));
        return response.Resource;
    }
}

Question: Are there any other methods in CosmosDB client which can return the document using the PartitionKey ONLY without the need of Id which I don't know ?

1 Answers

When selecting documents you could try to use QueryDefinition + QueryAsync:

var query = new QueryDefinition("select top 1 * from c");
var partitionKey = "PARTITIONKEY";
var resultSet = container.GetItemQueryIterator<ModelObject>(query, null, new QueryRequestOptions { PartitionKey = new PartitionKey(partitionKey) });
var result = new List<ModelObject>();

while (resultSet.HasMoreResults)
{
    var item = await resultSet.ReadNextAsync(ct /* CancellationToken */).ConfigureAwait(false);
    var itemList = item.ToList();
    result.AddRange(itemList);
}

Instead of a top 1 select you could also do a select * (for example)

Related