Defrost, then group groups in MongoDB C #

I am having problems with the new MongoDB C # 2.0 driver and aggregation pipeline.

Basically, I am trying to return the most popular elements in an array field of an object. Field Type: IList<string> FavouritePlaceIds { get; set; } IList<string> FavouritePlaceIds { get; set; } IList<string> FavouritePlaceIds { get; set; } .

I have the following MongoDB aggregation that works as expected:

 db.users.aggregate([ { $unwind : "$FavouritePlaceIds" }, { $group: { "_id": "$FavouritePlaceIds", "count": {$sum: 1}}}, { $sort : { "count": -1 }} ]) 

However, the problem now is to translate this code into C # using the new MongoDB 2.0 driver. I used the following link for help on the aggregation pipeline: http://mongodb.imtqy.com/mongo-csharp-driver/2.0/reference/driver/crud/reading/#unwind

I have the following for my aggregation pipeline:

 var pipeline = usersCollection.Aggregate() .Unwind(i => i.FavouritePlaceIds) .Group(i => i.FavouritePlaceIds, g => new { FavouritePlaceIds = g.Key, Count = g.Count() }) .SortByDescending(i => i.Count); 

When I proceed to compile this code, I get the following message:

"BsonDocument" does not contain a definition for "FavoritePlaceIds" and does not use the extension method "FavoritePlaceIds", which takes the first argument of type "BsonDocument" ...

The error occurs when the first parameter ( i => i.FavouritePlaceIds ) of the Group () method.

Reading notes from the link provided in the group section, it mentions that:

Since $ unwind is a projection type, you must specify a return type.

So, I assume that I am not specifying the correct return type, so it expects a BsonDocument object and cannot compile.

So, how can I specify the correct return type to use in the Group method?

+5
source share
1 answer

When you let Unwind print type parameters, it will use the collection type for TResult and BsonDocument for TNewResult .

If you want to use a specific type, not BsonDocument , you need to add these type parameters:

 var pipeline = usersCollection.Aggregate() .Unwind<OriginalType, NewResultType>(.... 

As always, you need to make sure that the operation actually returns what could be of this type.

+4
source

All Articles