Bendomin
Bendomin

Reputation: 45

How to get all items of container in cosmos db with dotnet core

Hi I would like to get all items of a container in a database in cosmos DB. I can see that there are already a lot of methods available but I don't see any getAllItems or a lookalike.

Is there an easy way to do it like using LINQ or something?

Thanks

Upvotes: 4

Views: 20277

Answers (2)

Will V
Will V

Reputation: 390

If you want to do this using Linq, you can do the following (As suggested in this answer here: How can I use LINQ in CosmosDB SDK v3.0 async query?):

var db = Client.GetDatabase(databaseId);
var container = db.GetContainer(containerId);

var q = container.GetItemLinqQueryable<Person>();
var iterator = q.ToFeedIterator();
var results = await iterator.ReadNextAsync();

If you want a non-Linq solution, use this (taken from the v3 SDK samples: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/ItemManagement/Program.cs#L259:

QueryDefinition query = new QueryDefinition(
            "select * from sales s where s.AccountNumber = @AccountInput ")
            .WithParameter("@AccountInput", "Account1");

        FeedIterator<SalesOrder> resultSet = container.GetItemQueryIterator<SalesOrder>(
            query,
            requestOptions: new QueryRequestOptions()
            {
                PartitionKey = new PartitionKey("Account1"),
                MaxItemCount = 1
            });

        while (resultSet.HasMoreResults)
        {
            FeedResponse<SalesOrder> response = await resultSet.ReadNextAsync();
            // Work through iterator list here
        }

Hope this helps!

Upvotes: 9

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

You can use LINQ like described in Microsoft Azures documentation.

Something like this should be the solution of your problem:

var db = Client.GetDatabase(databaseId);
var container = db.GetContainer(containerId);
//Get iterator or use some LINQ queries here
var iterator = container.GetItemLinqQueryable<YourType>().GetEnumerator();

Upvotes: 4

Related Questions