// mongo type for User
public class User
{
public User()
{
AppIntegrations = new UserAppIntegration[] { };
}
public string Id { get; set; }
public string Email { get; set; }
public UserAppIntegration[] AppIntegrations { get; set; }
}
public class UserAppIntegration
{
public string AppName { get; set; }
public string AppUserId { get; set; }
public bool UsedForLogin { get; set; }
public string AccessToken { get; set; }
public DateTime? TokenExpiry { get; set; }
}
// type used for projection - array of these to be returned by service
public class UserAppIntegrationStatus
{
public string AppName { get; set; }
// todo : other fields here...
}
// prepare query and count
var query = _collection.AsQueryable().OfType<User>();
if (filter != null)
{
query = query.Where(filter);
}
// slice, project and execute
query = query.Skip(skip);
query = query.Take(take);
var projected = query.Select(projection);
var results = projected.ToArray();
return results;
This is my fork, a little behind the master now: https://github.com/kierenj/mongo-csharp-driver
(See also my workaround commit there to get generic types working correctly. It's the non-backwards-compatible patch)
In fact I've tried a few ways to get this kind of projection to work. I'm leveraging the LINQyness, which works excellently of course, but am happy to take a more difficult route if needed.
Thanks Craig,
Kieren
var pipeline = col.Aggregate() .Match(u => u.Id == "1") .Project(u => new { SomeField = u.AppIntegrations.Select(i => new UserAppIntegrationStatus { AppName = i.AppName, CanRemove = !i.CanRemove }) });
I've filed a ticket here: https://jira.mongodb.org/browse/CSHARP-1306. I also filed CSHARP-1301 about the LINQ problem with $pull: https://jira.mongodb.org/browse/CSHARP-1301.
Thanks for the report,
Craig
It's a shame, since I just managed to put together some unit tests and modify everything to get as far as this (though probably still not correct, even if it was possible), I was quite proud:
{ "aggregate" : "testcollection", "pipeline" : [{ "$project" : { "Result" : { "$elemMatch" : { "G.E.F" : 33 } }, "_id" : 0 } }], "cursor" : { } }
I guess then IMongoCollection.AsQueryable() always uses the aggregation framework - no way to do LINQ with standard Find()s etc or any other workarounds for this one?
Kieren