Aggregation Functions in C#

3,851 views
Skip to first unread message

Anand Dayalan

unread,
May 22, 2012, 1:19:39 PM5/22/12
to mongodb-user
How do I execute the following statement in C#?

db.orders.aggregate([
{ $group: {_id:"$cust_id",total:{$sum:"$price"}} }
])

Robert Stam

unread,
May 22, 2012, 2:53:30 PM5/22/12
to mongod...@googlegroups.com
All drivers are slated to have some form of helper method for aggregation in the future. But aggregations are just commands, and you can write them yourself with the current version of the C# driver using RunCommand.

Your sample aggregation command is really just a shortcut for:

> db.runCommand({aggregate:"orders", pipeline:[{$group:{_id:"$cust_id",total:{$sum:"$price"}}}]})

Which you can write in C# as:

    var pipeline = new BsonArray
    {
        new BsonDocument { { "$group", new BsonDocument { { "_id", "$cust_id" }, { "total", new BsonDocument { { "$sum", "$price" } } } } } }
    };
    var aggregationCommand = new CommandDocument
    {
        { "aggregate", "orders" },
        { "pipeline", pipeline }
    };
    var commandResult = database.RunCommand(aggregationCommand);
    var results = commandResult.Response["result"].AsBsonArray;
    foreach (BsonDocument document in results)
    {
        // process result
    }



--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

Anand Dayalan

unread,
May 22, 2012, 3:25:46 PM5/22/12
to mongodb-user
Thanks Robert.

I found grouping by multiple keys can be done as show below.

db.runCommand({ "aggregate" : "Tablename", "pipeline" : [{ "$group" :
{ "_id" : {key1:"$AssociatedEntityId",key2:"$Data.C_338"}, "total" :
{ "$sum" : "$Data.C_333" } } }] })

Thanks,
Anand

Robert Stam

unread,
May 22, 2012, 3:37:15 PM5/22/12
to mongod...@googlegroups.com
Glad you figured it out.

As you found out, to group on multiple fields you group on a compound key, not on an array.

Sufyan Jamil

unread,
Mar 30, 2016, 11:23:35 AM3/30/16
to mongodb-user
anyone have any example of execution find query using runCommand?


Regards
Reply all
Reply to author
Forward
0 new messages