首页 > 解决方案 > 如何使用 LINQ 的 AsQueryable() 从 MongoDB 的内部数组中获取数据?

问题描述

我无法从 MongoDB 的内部数组中获取数据。我得到错误:

BsonSerializationException: No matching creator found.

这是我在 MongoDB、查询和环境中的数据示例。

{
        "Id" : 1,
        "compName" : "Samsung Electronics Co.",
        "symbol" : "005930-KRX",
        "analyst" : [
                {
                        "analystId" : 4,
                        "analystInit" : "SJ",
                        "analystFName" : "Steve",
                        "analystLName" : "Jobs",
                        "analystEmail" : "steve.jobs@apple.com"
                }
        ],
        "associates" : [
                {
                        "analystId" : 7,
                        "analystInit" : "BG",
                        "analystFName" : "Bill",
                        "analystLName" : "Gates",
                        "analystEmail" : "bill.gates@microsoft.com"
                },
                {
                        "analystId" : 10,
                        "analystInit" : "MJ",
                        "analystFName" : "Michael",
                        "analystLName" : "Jordan",
                        "analystEmail" : "michael.jordan@nba.com"
                }
        ],
        "gics" : "75301020",
        "cusip" : null
}

POCO

[BsonIgnoreExtraElements]
class CompanyClass
{
    #region [ Properties ]
    [BsonElement("issuerId")]
    public Int32 IssuerId { get; set; }
    [BsonElement("compName")]
    public string CompName { get; set; }
    [BsonElement("symbol")]
    public string Symbol { get; set; }
    [BsonElement("analyst")]
    public IEnumerable<AnalystClass> Analyst { get; set; }
    [BsonElement("associates")]
    public IEnumerable<AnalystClass> Associates { get; set; }
    [BsonElement("gics")]
    public string Gics { get; set; }
    [BsonElement("cusip")]
    public string Cusip { get; set; }
    #endregion
}
[BsonIgnoreExtraElements]
class AnalystClass
{
    #region [ Properties ]
    [BsonElement("init")]
    public string ResAnInit { get; set; }
    [BsonElement("firstName")]
    public string ResAnFirstName { get; set; }
    [BsonElement("lastName")]
    public string ResAnLastName { get; set; }
    [BsonElement("email")]
    public string ResAnEmail { get; set; }
    #endregion
}

询问:

compCollection = GetMonDB("Companies").GetCollection<CompanyClass>("coverage");
var comps = compCollection.AsQueryable()
.Select(c => new { 
    CompName = c.CompName,
    Symbol = c.Symbol,
    ResAnsFName = c.Analyst.Select(x => x.ResAnFirstName)  <-- Problem line
    CUSIP = c.Cusip
});

我想得到这个:

在此处输入图像描述

我的环境:

C# MongoDB.Driver = 2.12
MongoDB = 4.2
Windows = Win10

看来我错过了一些明显的东西。我究竟做错了什么?

标签: c#mongodblinqasqueryable

解决方案


只需像这样进行投影:

var comps = await compCollection
    .AsQueryable()
    .Select(c => new
    {
        ...
        ResAnsFName = c.Analyst.first().ResAnFirstName
        ...
    })
    .ToListAsync();

推荐阅读