MongoDB C# 驱动程序 2.0:如何从 MapReduceAsync 获取结果

2024-01-09

MongoDB C# 驱动程序 2.0:如何从 MapReduceAsync 获取结果

我正在使用 MongoDB 版本 3、C# 驱动程序 2.0,并将获得 MapReduceAsync 方法的结果。 我有这个集合“用户”:

{ "_id" : 1, "firstName" : "Rich", "age" : "18" }
{ "_id" : 2, "firstName" : "Rob", "age" : "25" }
{ "_id" : 3, "firstName" : "Sarah", "age" : "12" }

Visual Studio 中的代码:

var map = new BsonJavaScript( @"
    var map = function()
    {
        emit(NumberInt(1), this.age);
    };");

var reduce =  new BsonJavaScript(@"
    var reduce = function(key, values)
    {
        var sum = 0;

        values.forEach(function(item)
        {
            sum += NumberInt(item);
        });

        return sum;
    };");

var coll = db.GetCollection<BsonDocument>("users");
var options = new MapReduceOptions<BsonDocument, TResult>();//what should be TResult?

options.OutputOptions = MapReduceOutputOptions.Inline;

var res = coll.MapReduceAsync(map, reduce, options).Result.ToListAsync();

//get the values of res...

//or if the result is a list...
foreach(var item in res)
{
    //get the values and do something...
}

TResult 可以是 BsonDocument 或表示类型reduce item 结果的特定类。

我认为对于你的例子,你可以有一个像这样的通用类:

public class SimpleReduceResult<T>
{
    public string Id { get; set; }

    public T value { get; set; }
}

你的选项声明是

var options = new MapReduceOptions<BsonDocument, SimpleReduceResult<int>>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MongoDB C# 驱动程序 2.0:如何从 MapReduceAsync 获取结果 的相关文章

随机推荐