![](/img/trans.png)
[英]how to read derived object from cosmos db with document db client from C#
[英]How to read boolean value from Cosmos DB from C#
我在documentdb
有一些具有以下结构的数据:
{
id:1,
key:"USA",
states:["New York","New Jersey", "Ohio", "Florida" ]
}
我需要检查,如果“加利福尼亚”是从使用C#查询上述文件中提供CreateDocumentQuery
返回真/假。 如何从CreateDocumentQuery
读取boolean
值?
假设你有一个看起来像这样的 DTO:
class Item
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("states")]
public List<string> States { get; set; }
}
您可以对数组使用Contains
方法来检查该值是否存在。 LINQ to SQL 转换器会将其转换为 sql 查询。 您所要做的就是在 where 子句中添加任何其他谓词并运行它。 我故意只选择文档的 Id 来保存一些 RU 并使其运行得更快。
如果您在 where 子句中的表达式中添加分区键,或者您知道分区键值是什么,请在提要选项中设置它以提高性能。 不建议将跨分区查询作为日常工作流程的一部分。
您可以使用 DocumentQueryable 的CountAsync()
扩展方法来获取与谓词匹配的文档数,然后执行 a > 0
以查看它是否存在。
这是代码:
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;
}
但是,下面的代码将控制查询并在第一次匹配时退出,这将比上面的代码更有效。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.