簡體   English   中英

C# MongoDB.Driver sortBy 屬性中的數組元素

[英]C# MongoDB.Driver sortBy element in property that is an array

我有這樣的文檔結構:

public class CountryDomain{
  public string Iso2 {get;set;}
  public List<EntityName> Names {get;set;}
}

public class EntityName{
   public string Culture {get;set;}
   public string Name {get;set;}
}

這導致像這樣的文件

{
 Iso2: "th",
 Names: [
   {Culture: "nl", Name: "Thailand"},
   {Culture: "en", Name: "Thailand"}
 ]
}

現在我想獲得按“nl”文化名稱排序的國家/地區列表。

通過這樣做按 ISO2 排序:

var collection = Context.Database.GetCollection<CountryDomain>(Table);
return collection.Aggregate().SortByDescending(e => e.Iso2).ToList();

但是我如何根據CulturenlNames數組中的Name值對其進行排序。 我嘗試過類似的方法,但 MongoDB 驅動程序無法對其進行序列化。

var collection = Context.Database.GetCollection<CountryDomain>(Table);
return collection.Aggregate().SortByDescending(e => e.Names.FirstOrDefault(x=> x.Culture == "nl").ToList();

就 MongoDB 直接查詢而言,我認為您需要采用此 playground 示例中演示的方法。 基本上,您需要首先在聚合中執行$addFields以從數組中提取要排序的值。 然后,您可以在后續排序規范中使用該生成的字段名稱,然后在需要時將其刪除。

之所以在評論中詢問結果集的大小,是因為這個操作將無法使用索引來提供排序。 因此,如果返回的結果(與集合中的文檔數量相對)很大,那么此操作的性能可能不是特別好,並且可能會在這樣做時消耗大量系統資源。 這不是完全避免它的理由,但肯定是需要注意的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM