【问题标题】:.NET Driver with LINQ: NotSupportedException: $project or $group带有 LINQ 的 .NET 驱动程序:NotSupportedException: $project 或 $group
【发布时间】:2016-08-18 16:54:54
【问题描述】:

以下查询有效:

return Database
    .GetCollection<MyEntity>()
    .AsQueryable()
    .Where(x => x.StartDate <= instance && x.EndDate >= instance)
    .GroupBy(x => x.Key.Guid)
    .Select(x => x.First().Id)
    .ToList();

但是,当添加 $in 条件时(见下文),会抛出以下异常:

应用程序引发了未处理的异常。 System.NotSupportedException: $project 或 $group 不支持 首先({document}{_id})

return Database
    .GetCollection<MyEntity>()
    .AsQueryable()
    .Where(x => guidKeys.Contains(x.Key.Guid)) // $in condition
    .Where(x => x.StartDate <= instance && x.EndDate >= instance)
    .GroupBy(x => x.Key.Guid)
    .Select(x => x.First().Id)
    .ToList();

我知道驱动程序还不支持很多 LINQ,但我不明白引入加法匹配阶段(使用 $in)如何导致分组阶段不兼容。

有人能解释为什么会这样吗?

我正在使用带有 .NET 驱动程序 2.2.2 的 MongoDB 3.2。

编辑:

MyEntity 看起来像这样:

[BsonIgnoreExtraElements]
public class MyEntity: BaseMongoDocument
{
    [BsonId]
    [BsonRepresentation(BsonType.Binary)]
    public Guid Id { get; set; }

    [BsonRequired]
    [BsonElement("startDate")]
    public DateTime StartDate { get; set; }

    [BsonRequired]
    [BsonElement("endDate")]
    public DateTime EndDate { get; set; }

    [BsonRequired]
    [BsonElement("key")]
    public SquidDocument Key { get; set; }

    [BsonConstructor]
    private MyEntity()
    { }
}

public class SquidDocument
{
    [BsonRequired]
    [BsonElement("guid")]
    public Guid Guid { get; private set; }

    [BsonRequired]
    [BsonElement("squid")]
    public string Squid { get; private set; }

    [BsonConstructor]
    private SquidDocument(Guid guid, string squid)
    {
        Guid = realSquid.Guid;
        Squid = realSquid.Value;
    }
}

【问题讨论】:

  • 正如错误提示和您上面提到的,MongoDB 驱动程序没有完全实现 LINQ,$in 运算符也是如此。
  • $in 当然是支持的。我正在分组处理第一个查询。
  • 嗯,我在第一个查询中没有看到 $in。
  • 这就是重点。第一个查询(没有 $in)工作正常。第二个查询(与第一个查询完全相同,但带有 $in 条件)在分组中出现 NotSupportedException 失败。
  • MyEntity 是什么样的(任何引用的类)?

标签: mongodb mongodb-query mongodb-.net-driver


【解决方案1】:

您的问题很可能不在您的 mongo 查询中,而是在 [guidKeys] 的解析中。因为 linq 会延迟执行,而 mongo 驱动程序不支持 linq,所以无法解析 [guidKeys.Contains] 和 barfs。将您的 guidKeys 转换为列表或数组,它可能会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多