簡體   English   中英

MongoDB LINQ選擇具有特定條件的數組元素

[英]MongoDB LINQ select array elements with specific conditions

這是我的MongoDB數據結構:

public class Part : ICloneable
    {
        string _id;
        ObservableCollection<DataElement> PartData;
        ObservableCollection<DataElement> SensorData;
    }
    public class DataElement: ICloneable
    {
        string description;
        string[] values;
    }

我想使用Linq讀取有關SensorData,PartData和ResultData元素的$projected / reduce的所有部件,並提供特定說明。

例:

Part{
_id: id1,
PartData[
    {description: "des1", values: "val1"},
    {description: "des2", values: "val2"}
],
SensorData[
    {description: "des3", values: "val5"},
    {description: "des4", values: "val2"},
    {description: "des5", values: "val2"}
]}

應該在描述為“ des2”,“ des4”和“ des5”的所有元素上投影/縮減,以使讀取的數據看起來像

Part{
_id: id1,
PartData[
    {description: "des2", values: "val2"}
],
SensorData[
    {description: "des4", values: "val2"},
    {description: "des5", values: "val2"}
]}

每個描述都是唯一的,但並非每個部分都包含所有描述。

有沒有$ unwind / SelectMany的簡單解決方案嗎? 就像是

Select(p => p.PartData[] where p.PartData.Description == specifiedDescription),
p => p.SensorData[] where p.SensorData.Description == specifiedDescription))

但包括完整的數組元素,而排除其他元素以及PartData和SensorData?

編輯:Veeram的答案后,我試圖實現以下內容:

parts = db.GetCollection<Part>("Part");        
var pipeline = parts.Aggregate()
.Project(p => new
{  PartData = p.PartData.Where(d => d.Description == specifiedDescription),
  SensorData = p.SensorData.Where(s => s.Description == specifiedDescription)
 }) ;
 var query = pipeline.ToEnumerable().AsQueryable();
 var returnParts = new ObservableCollection<Part>(query);

但這會導致pipeline成為匿名IAggregateFluent<'a>而不是IAggregateFluent<Part> ,這使query成為匿名IQueryable<'a >,因此導致編譯錯誤“無法從匿名IQueryable<'a >轉換IQueryable<'aIQueryable<Part> “在插入query作為參數對的構造ObservableCollection<Part>()

沒有$select ,變量將不再是匿名的,而是類<Part> ,並且不會發生編譯錯誤。 顯然, $select更改了聚合的類。

如何解決這個錯誤? 我的想法是在不生成新類的情況下創建$project ,而是重置當前類<Part>某些字段,但是如何實現呢?

您可以在$project階段通過聚合管道使用$filter運算符。

var pipeline = 
      collection.
            Aggregate()
              .Project(
                 p => new {
                  PartData= p.PartData.Where(d => d.Description == specifiedDescription),
                  SensorData= p.SensorData.Where(s=> s.Description == specifiedDescription)
            }
      );

暫無
暫無

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

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