$project or $group does not support <document>

谁说我不能喝 提交于 2019-12-19 06:41:03

问题


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);

I thought IndexOfCP is supported.

What am i doing wrong here?


回答1:


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);

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.



来源:https://stackoverflow.com/questions/47383632/project-or-group-does-not-support-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!