【问题标题】:System.NotSupportedException: '$project or $group does not support {document}.' mongodbSystem.NotSupportedException: '$project 或 $group 不支持 {document}。' mongodb
【发布时间】:2018-06-08 13:25:01
【问题描述】:

当我尝试在 select 中执行 join 和 filter 时,mongodb 2.4.4 驱动器抛出此异常:

System.NotSupportedException: '$project 或 $group 不支持 {文档}。' mongodb

下面的加入和过滤有什么问题?

var appt = (from col1 in collection1.AsQueryable()
    join col2 in collection2.AsQueryable() on col1.Id equals col2.RefKey into grp
    select new {
        col1, filteredCol = col1.BandId == "" ? grp : grp.Where(t => t.Name ="Hello")
    }).Take(10).ToList();

【问题讨论】:

    标签: c# mongodb


    【解决方案1】:

    您的问题不是由加入或过滤引起的,而是由您的投影引起的。投影不应包含文档本身,这只是 MongoDB .Net 驱动程序不支持。

    因此,在投影中不包含 col1 对象的以下查询将正常工作:

    var appt = (from col1 in collection1.AsQueryable()
        join col2 in collection2.AsQueryable() on col1.Id equals col2.RefKey into grp
        select new
        {
            //col1,
            filteredCol = col1.BandId == "" ? grp : grp.Where(t => t.Name == "Hello")
        }).Take(10).ToList();
    

    这里有几个可能的修复方法。最好的选择是在投影中不包括整个文档,而只包括进一步逻辑实际需要的字段,例如:

    var appt = (from col1 in collection1.AsQueryable()
        join col2 in collection2.AsQueryable() on col1.Id equals col2.RefKey into grp
        select new
        {
            col1.Id,
            col1.BandId,
            filteredCol = col1.BandId == "" ? grp : grp.Where(t => t.Name == "Hello")
        }).Take(10).ToList();
    

    如果您需要文档对象本身,您可以使用 .AsEnumerable() 将整个集合获取到客户端,然后使用 LINQ to objects:

    var appt = (from col1 in collection1.AsQueryable().AsEnumerable()
        join col2 in collection2.AsQueryable() on col1.Id equals col2.RefKey into grp
        select new
        {
            col1,
            filteredCol = col1.BandId == "" ? grp : grp.Where(t => t.Name == "Hello")
        }).Take(10).ToList();
    

    将此方法用作最后一个选项,因为它对服务器和客户端的负载都很大。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多