简体   繁体   中英

How to read boolean value from Cosmos DB from C#

I have some data in documentdb with following structure:

{    
  id:1,    
  key:"USA",  
  states:["New York","New Jersey", "Ohio", "Florida" ]         
}

I need to check if "California" is available in the above document with a query from C# using CreateDocumentQuery which returns true/false. How can I read the boolean value from CreateDocumentQuery ?

Assuming you have a DTO looking something like this:

class Item
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("key")]
    public string Key { get; set; }

    [JsonProperty("states")]
    public List<string> States { get; set; }
}

You can use the Contains method on an array to check if the value exists or not. The LINQ to SQL converter will turn this into a sql query for you. All you have to do is to add any other predicates in the where clause and run it. I am intentionally only selecting the Id of the document to make save some RUs and make it run faster.

If you add the partition key in the expression present in the where clause, or if you know what the partition key value is, please set it in the feed options to enhance performance. Cross partition queries are not really recommended as part of your day to day workflow.

You can use the CountAsync() extension method of the DocumentQueryable to get the count of doucments matching the predicate and then do a > 0 to see if it exists.

Here is the code for that:

public async Task<bool> ArrayContainsAsync()
{
    var documentClient = new DocumentClient(new Uri("https://localhost:8081"), "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
    var collectionUri = UriFactory.CreateDocumentCollectionUri("dbname", "collectionName");
    return (await documentClient
                      .CreateDocumentQuery<Item>(collectionUri, new FeedOptions { EnableCrossPartitionQuery = true })
                      .Where(x => x.States.Contains("California")).CountAsync()) > 0;
}

However, the code below will take control of the query and exit on first match which will be way more efficient than the code above.

public async Task<bool> ArrayContainsAsync()
{
    var documentClient = new DocumentClient(new Uri("https://localhost:8081"), "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
    var collectionUri = UriFactory.CreateDocumentCollectionUri("dbname", "collectionName");
    var query = documentClient
        .CreateDocumentQuery<Item>(collectionUri, new FeedOptions { EnableCrossPartitionQuery = true })
        .Where(x => x.States.Contains("California")).Select(x=> x.Id).AsDocumentQuery();

    while (query.HasMoreResults)
    {
        var results = await query.ExecuteNextAsync();
        if (results.Any())
            return true;
    }

    return false;
}

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