I have a type called Student with three properties:
| Student |
|------------------------|
| Id: string |
| Name: string |
| CoursesTaken: string[] |
The CoursesTaken
property holds the id's of the courses taken, in the order they were taken, so the last element in that array will be the id of the last course that a student took.
Now I want to query the collection for students who´s last taken course was X. And I'm guessing the ProjectionDefinitionBuilder<Student>.Slice
is the method to use.
And I don't want to resort to BsonDocuments, because I'd like to preserve type inference throughout the whole thing, since I'm adding more filters later on. So I would like to pass in an IAggregateFluent<Student>
and I want an IAggregateFluent<Student>
back.
Is there anyway to achieve this?
The reason I couldn't get Ryans example (below) to work was that I wasn't actually following it completely. This is what I found:
// This doesn't work (throws a NotSupportedException):
contacts.Aggregate()
.Project(s => new
{
Fruit = s,
LastNode = s.Path.Last()
})
.Match(x => x.LastNode == "avacados")
.Project(x => x.Fruit);
// But this one works:
contacts.Aggregate()
.Project(s => new
{
Id = s.Id,
Name = s.Name,
Path = s.Path,
LastNode = s.Path.Last()
})
.Match(x => x.LastNode == "avacados")
.Project(x => new Fruit
{
Path = x.Path,
Id = x.Id,
Name = x.Name
});
this seems to work but it's not ideal due to the projections.
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
});
here's a full test program
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();
}
}
}