13

我在使用新的 C# 2.0 MongoDB 驱动程序和聚合管道时遇到了一些问题。

基本上,我试图在对象的数组字段中返回最受欢迎的元素。字段类型为:IList<string> FavouritePlaceIds { get; set; }

我有以下 MongoDB 聚合,它按预期工作:

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

但是,现在的问题是尝试使用新的 MongoDB 驱动程序 2.0 将其转换为 C# 代码。我一直在使用以下链接来获取聚合管道的帮助:http: //mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/crud/reading/#unwind

到目前为止,我的聚合管道有以下内容:

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

当我去编译该代码时,我收到以下消息:

“BsonDocument”不包含“FavouritePlaceIds”的定义,并且找不到接受“BsonDocument”类型的第一个参数的扩展方法“FavouritePlaceIds”......

错误发生在i => i.FavouritePlaceIdsGroup() 方法的第一个参数 ( ) 上。

阅读组部分下提供的链接中的注释,它提到:

因为 $unwind 是一种投影类型,所以您必须提供返回类型。

所以,我假设我没有指定正确的返回类型,这就是为什么它需要一个 BsonDocument 对象,并且无法编译。

那么,如何在 Group 方法中指定正确的返回类型呢?

4

1 回答 1

10

当您让Unwind推断类型参数时,它将使用集合类型 forTResultBsonDocumentfor TNewResult

如果你想使用特定类型而不是BsonDocument你需要添加这些类型参数:

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

与往常一样,您需要确保操作实际上返回了可以属于该类型的内容。

于 2015-05-26T05:58:07.567 回答