简体   繁体   中英

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)

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM