MongoDB C# driver 2.0: How to get the result from MapReduceAsync

浪子不回头ぞ 提交于 2019-12-07 17:38:57

问题


MongoDB C# driver 2.0: How to get the result from MapReduceAsync

I'm using MongoDB version 3, C# driver 2.0 and would get the result of MapReduceAsync method. I have this collection "users":

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

The code in VisualStudio:

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...
}

回答1:


TResult can be a BsonDocument or a specific class which represent the result of type reduce item.

I think for your example, you could have a generic class like this :

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

    public T value { get; set; }
}

And your options declaration would be

var options = new MapReduceOptions<BsonDocument, SimpleReduceResult<int>>();


来源:https://stackoverflow.com/questions/31776621/mongodb-c-sharp-driver-2-0-how-to-get-the-result-from-mapreduceasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!