$ project或$ group不支持< document> [英] $project or $group does not support <document>

查看:243
本文介绍了$ project或$ group不支持< document>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用投影运行聚合,但得到NotSupportedException: $project or $group does not support <document>.我正在使用mongodb v3.4运行2.4.4版的驱动程序.

I'm trying to run aggregate with projection but i get NotSupportedException: $project or $group does not support <document>. I am running version 2.4.4 of driver with mongodb v3.4.

var filter = Builders<T>.Filter.Regex(x=>x.Value,"/test/gi");

var aggregate = collection.Aggregate()
       .Match(filter)
       .Project(x => new 
       {
          Idx = x.Value.IndexOf("test"),
          Result = x
       })
       .SortBy(x => x.Idx);

我认为IndexOfCP我在这里做错什么了?

推荐答案

问题不是由IndexOf引起的,而是由您的投影引起的.投影不应该包含文档本身,MongoDB .Net驱动程序不支持此文件. 因此,下面的查询中不包含x对象到投影中就可以了:

The problem is caused not by IndexOf but by your projection. Projection should not include document itself, this just is not supported by MongoDB .Net driver. So the following query without including x object into projection will work just fine:

var aggregate = collection.Aggregate()
       .Match(filter)
       .Project(x => new 
       {
          Idx = x.Value.IndexOf("test"),
          // Result = x
       })
       .SortBy(x => x.Idx);

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

There are several possible fixes here. The best choice is to include in projection not the whole document but only the fields that are actually required for further logic, e.g.:

var aggregate = collection.Aggregate()
    .Match(filter)
    .Project(x => new
    {
        Idx = x.Value.IndexOf("test"),
        Value = x.Value,
        // ...
    })
    .SortBy(x => x.Idx);

但是,如果您需要文档对象本身,则可以将整个集合获取到客户端,然后对对象使用LINQ:

If however you need the document object itself, you could fetch the whole collection to the client and then use LINQ to objects:

var aggregate = collection.Aggregate()
    .Match(filter)
    .ToList()
    .Select(x => new
        {
            Idx = x.Value.IndexOf("test"),
            Result = x
        })
        .OrderBy(x => x.Idx);

使用此方法作为最后一个选择,因为它会大量负载服务器和客户端.

Use this approach as last option because it loads heavily both server and client.

这篇关于$ project或$ group不支持&lt; document&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆