user1438940
user1438940

Reputation: 3231

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)

Upvotes: 5

Views: 10919

Answers (2)

shA.t
shA.t

Reputation: 16968

In MongoDB CSharp Drivers 2.0.0+:
I use below syntax to run such commands:

var command = new CommandDocument
{
    {"aggregate", "TestCollection"},
    {
        "pipeline", new BsonArray
        {
            new BsonDocument {{"$unwind", "$Tags"}},
            new BsonDocument
            {
                {
                    "$group", new BsonDocument
                    {
                        {"_id", "$Tags"},
                        {"count", new BsonDocument {{"$sum", 1}}}
                    }
                }
            }
        }
    }
};

var result = db.RunCommand<BsonDocument>(command)["result"]
    .AsBsonArray.ToList();

Upvotes: 1

philnate
philnate

Reputation: 1506

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

Upvotes: 5

Related Questions