2017-07-26 95 views
0

在DocumentDb中,是否可以搜索子文檔以獲取父文檔?如何查詢嵌入式數據documentDB以檢索父文檔

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

    [JsonProperty(PropertyName = "name")] 
    public string Name { get; set; } 

    [JsonProperty(PropertyName = "locations")] 
    public List<Location> Locations { get; set; } 

    public Customer() 
    { 
     Locations = new List<Location>(); 
    } 
} 

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

    [JsonProperty(PropertyName = "city")] 
    public string City{ get; set; } 

    [JsonProperty(PropertyName = "state")] 
    public string State{ get; set; } 

} 

在文檔資源管理器,我可以看到我有這個階級結構的一個實例,像這樣:

{ 
    "id": "7", 
    "name": "ACME Corp", 
    "location": [ 
    { 
     "id": "c4202793-da55-4324-88c9-b9c9fe8f4b6c", 
     "city": "newcity", 
     "state": "ca" 
    } 
    ] 
}, 
{ 
    "id": "35", 
    "name": "Another Corp", 
    "location": [ 
    { 
     "id": "d33e793-da55-4324-88c9-b9c9fe8f4baa", 
     "city": "newcity", 
     "state": "ca" 
    } 
    ] 
} 

有沒有一種方法來查詢等,其中城市=「newcity」嵌入數據和狀態=「ca」 但檢索父數據?如果我使用SelectMany(x => x.Locations)查詢子項,那麼它將獲取位置數據而不是根(客戶)文檔。

感謝

回答

2

有沒有一種方法來查詢等,其中城市=「newcity」和狀態=「CA」,但檢索父數據嵌入的數據?

是的,我們可以使用加入做到這一點。更多詳情請參考Advanced database concepts and SQL queries

SELECT c.id as id ,c.name as name,l as location from customer c Join l in 
c.location where l.city = 'newcity' and l.state = 'ca' 

它返回

enter image description here

C#代碼演示:多

FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 }; 
var customerQuery = client.CreateDocumentQuery<dynamic>(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), 
       "SELECT c.id as id, c.name as name, l as location from customer c Join l in c.location where l.city = 'newcity' and l.state = 'ca'", 
       queryOptions).AsDocumentQuery(); 

var customerList = new List<dynamic>(); 
while (customerQuery.HasMoreResults) 
{ 

    customerList.AddRange(customerQuery.ExecuteNextAsync<dynamic>().Result); 

} 

enter image description here

+0

哇,感謝您的代碼,甚至截屏! – wil

相關問題