在保留类型信息的同时使用Slice投影

问题描述 投票:1回答:1

我有一个叫做Student的类型,具有三个属性:

| Student                |
|------------------------|
| Id: string             |
| Name: string           |
| CoursesTaken: string[] |

[CoursesTaken属性按所上课的顺序保存所修课程的ID,因此该数组中的最后一个元素将是学生所修课程的ID。

现在,我要查询最近参加的课程是X的学生的集合。我猜想ProjectionDefinitionBuilder<Student>.Slice是要使用的方法。

而且我不想求助于BsonDocuments,因为我想在整个过程中保留类型推断,因为稍后我将添加更多过滤器。因此,我想传递IAggregateFluent<Student>,并希望返回IAggregateFluent<Student>

反正有实现此目标的方法吗?

c# mongodb mongodb-.net-driver
1个回答
0
投票

这似乎可行,但由于预测而并不理想。

            var query = collection.Aggregate()
                                  .Project(s => new
                                  {
                                      s.Id,
                                      s.Name,
                                      s.CoursesTaken,
                                      lastCourse = s.CoursesTaken.Last()
                                  })
                                  .Match(x => x.lastCourse == "avacados")
                                  .Project(x => new Student
                                  {
                                      Id = x.Id,
                                      Name = x.Name,
                                      CoursesTaken = x.CoursesTaken
                                  });

这里是完整的测试程序

using MongoDB.Driver;
using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Linq;

namespace StackOverflow
{
    public class Student : Entity
    {
        public string Name { get; set; }
        public string[] CoursesTaken { get; set; }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            new DB("test", "localhost");

            (new Student
            {
                Name = "Harry Potter",
                CoursesTaken = new[] { "spells", "broomsticks", "avacados" }
            }).Save();

            var query = DB.Fluent<Student>()
                          .Project(s => new
                          {
                              s.ID,
                              s.Name,
                              s.CoursesTaken,
                              lastCourse = s.CoursesTaken.Last()
                          })
                          .Match(x => x.lastCourse == "avacados")
                          .Project(x => new Student
                          {
                              ID = x.ID,
                              Name = x.Name,
                              CoursesTaken = x.CoursesTaken
                          })
                          .ToList();            
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.