简体   繁体   中英

Count number of items in cosmos db?

I am currently intefacing my cosmos db, using EF core, and thought I could use linq queries to determine how many items currently resides within the db.

But when I do this

        var a = dbContext.Set<DbModel>().FirstOrDefault();

I get an error

A host error has occurred during startup operation '4332670c-85c3-4128-ba47-817b45c4a9d9'.
[2022-07-19T09:35:36.988Z] System.Linq.Expressions: Argument types do not match.
Value cannot be null. (Parameter 'provider')

How do determine wether my database contains any items? either via EF core, or through the cosmos client?


I try to reproduce same issue but not working. You can do by using this below code. This code is working but not using entity framework.

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp7
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string EndPointUri = "https://mydomain.documents.azure.com:443/";
            string PK = "CHATYXMWx3YFAwy55Ee4uI92TrUTwtbi7loAutVdPSB0Z3GdQcgZCGthWqZXv9v343urjrRfqV9x2I3xZZYFEQ==";

            DocumentClient cosmosClient = new DocumentClient(new Uri(EndPointUri), PK);

            string sqlQuery = "SELECT * FROM d";
            var dbs = cosmosClient.CreateDatabaseQuery(sqlQuery).ToList();

            foreach (var db in dbs)
            {
                Console.WriteLine("Database: " + db.id);
                Console.WriteLine("- Collections: ");

                List<DocumentCollection> collections = cosmosClient.CreateDocumentCollectionQuery((String)db._self).ToList();

                foreach (var collection in collections)
                {

                    var count = cosmosClient.CreateDocumentQuery<int>(collection.SelfLink, $"SELECT value count(1) FROM c",
                                    new FeedOptions() { EnableCrossPartitionQuery = true, MaxItemCount = 1, }).AsEnumerable().First();

                    Console.WriteLine("  - " + collection.Id + $", Count: " + count);
                }
                Console.WriteLine(Environment.NewLine);
            }
            Console.WriteLine("Finished reading all DB Collections");

            Console.ReadKey();
        }
    }
}

Cosmos Db在此处输入图像描述

Output在此处输入图像描述

These document will also help you by Microsoft Github onGet the Record Count in Cosmos DB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM