簡體   English   中英

如何使用Linq查詢Mongo C#2.2驅動程序中的嵌套列表?

[英]How to query nested list in Mongo C# 2.2 driver with Linq?

如何使用Linq進行聚合查詢。 我知道有一個AsQueryable()接口。 但是當我進行聚合時似乎會拋出錯誤。

如果我有一個名為person的集合存儲這樣的數據:

  {
    "Name": "Punny",
    "Interests": [
      1,
      2
    ]
  }

另一個名為interests集合存儲數據如下:

  {
    "_id":1,
    "name":"music"
  },
  {
    "_id":2,
    "name":"read"
  }

我想得到這樣的東西:

  {
    "Name": "Punny",
    "Interests": [
      "music",
      "read"
    ]
  }

如何通過Linq與AsQueryable實現這一AsQueryable 我試過這個:

_context.People.AsQueryable()
    .Select(p => new
    {
      Name = p.Name,
      Interests = p.InterestingIds
       .Join(_context.Interests.AsQueryable(),
        per => per,
        i => i.Id,
        (per, i) => new {i.Name})
    }).ToList();

它拋出System.NotSupportedException

System.NotSupportedException:表達式樹{document} {InterestingIds}中不支持類型System.Linq.Enumerable的連接.Join([FunnyMongoBlog.interest],per => per,i => i.Id,(per,i )=> new <> f__AnonymousType1`1(Name = i.Name))。

我嘗試了兩次數據庫:

      var person = _context.People.AsQueryable()
    .Single(p => p.Name == "Punny");
  var ids = person.InterestingIds;
  var query = _context.Interests.AsQueryable()
    .Where(i => ids.Contains(i.Id)).ToList();
  var result = new
  {
    person.Name,
    Interest = query
  };

這是有效的,但我想知道我們是否可以一次性完成,以便數據庫可以處理聚合。

你可以在聚合框架中做到這一點,但我建議在mongoDB中使用subDocumnets的強大功能,並將這些元素完全嵌入到主文檔中。 換句話說,我們需要從關系思維轉向文檔思維。

我建議的物體形狀:

{
    "Name" : "Punny",
    "Interests" : [{
            "_id" : 1,
            "name" : "music"
        }, {
            "_id" : 2,
            "name" : "read"
        }
    ]
}

在c#代碼中

class MyClass {
    public string Name;
    public List < Interest > Interests;
}

class Interest {
    public int Id;
    public string Name;
}

現在請查找所涉及的轉換所需的bson文檔:

db.col.aggregate([{
            $unwind : "$Interests"
        }, {
            $lookup : {
                from : "interests",
                localField : "Interests",
                foreignField : "_id",
                as : "interest"
            }
        }, {
            // now we need to reshape document
            $project : {
                _id : 1,
                Name : 1,
                Interests : "$interest.name"
            }
        },
        //group documents back
        {
            $group : {
                _id : {
                    id : "$_id",
                    name : "$Name"
                },
                Interests : {
                    $push : "$Interests"
                }
            }
        }, {
            //final reshape
            _id : "$_id.id",
            Name : "$_id.name",
            Interests : 1
        }
    ])

並決定嵌入是否值得一試:-)

歡迎任何評論!

暫無
暫無

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

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