Search code examples
c#.netc#-4.0mongodbmongodb-.net-driver

With the mongoDB C# driver, how do I issue a runCommand?


The mongoDB API documentation seems to be lacking in this area. I am trying to use the aggregate function to get a count of popular tags in a certain collection. Here is the command I wish to execute:

db.runCommand(
       { aggregate : "articles", 
         pipeline : [ { $unwind : "$Tags" }, 
                      { $group : { _id : "$Tags", count : { $sum : 1 } }
                      } ]});

When I execute this using the shell, I get the following:

{
    "result": [{
        "_id": "2012",
        "count": 3
    }, {
        "_id": "seattle",
        "count": 5
    }],
    "ok": 1
}

I'm using c# 4.0, so I guess I would prefer to get this back as a dynamic object, but I'll take whatever I can get...

FWIW, I am using mongoDB for Windows, 32 bit, v2.1.1 (Nightly)


Solution

  • Here's the corresponding C# Driver Doc page: RunCommand(). So basically you call Database.RunCommand("MyCommand"). This ticket in JIRA may come handy for an example of more complex commands requiring (multiple) properties: CSHARP-478