I am trying to do a MongoDB aggregate using LINQ, with the MongoDB .NET Driver version 2.1 and .NET 4.5, using ScottGu's Dynamic LINQ library.
This is a simplified schema for the data stored in MongoDB:
{
"_id" : "151207.01.02",
"project" : "SomeRandomProject",
"material" : "Azbantium",
"process" : "Paintball",
}
I have successfully used this to build a sort query with the following code (Where MyType is a POCO class used for MongoDB):
public static List<string> DynamicOrderAggregate(string parameter)
{
var client = new MongoClient(connectionString); // a static value not shown
var db = client.GetDatabase(database); // also a static value not shown
var col = db.GetCollection<MyType>(collection);
List<string> orderListString = new List<string>();
IQueryable<MyType> colQueryable = col.AsQueryable();
var orderedList = colQueryable
.OrderBy(parameter)
.Select(parameter);
foreach(var item in orderedList)
orderListString.Add(item)
return orderListString
}
This yields an aggregate equivalent of this when I look at the orderedList variable when debugging when inputting "material" as the parameter:
{aggregate([{ "$sort" : { "material" : 1 } }, { "$project" : { "material" : "$material", "_id" : 0 } }])}
And I am able to get a list of "materials" for each run.
However, when I try a group query using the following code (using the suggestion from this post: How to use GroupBy using Dynamic LINQ):
public static List<string> DynamicOrderAggregate(string parameter)
{
var client = new MongoClient(connectionString);
var db = client.GetDatabase(database);
var col = db.GetCollection<MyType>(collection);
List<string> groupListString = new List<string>();
IQueryable<MyType> colQueryable = col.AsQueryable();
var groupedList = colQueryable
.GroupBy(parameter, "it")
.Select(String.Format("new (it.Key as {0})", parameter));
foreach(var item in orderedList) // exception occurs here
groupListString.Add(item)
return groupListString
}
I'm seeing in the groupedList variable with an empty bracket and the query in some generic form:
{aggregate([]).GroupBy(Param_0 => Param_0.material, Param_1 => Param_1).Select(Param_2 => new DynamicClass1() {material = Param_2.Key})}
And I'm getting the following exception:
An unhandled exception of type 'System.NotSupportedException' occurred in MongoDB.Driver.dll
Additional information: The method GroupBy is not supported in the expression tree: aggregate([]).GroupBy(Param_0 => Param_0.material, Param_1 => Param_1).
I know that the .NET driver is relatively new. I really do need to be able to do dynamic queries that include grouping operations. Can anyone please advise?
Thanks kindly!
-- Ari