Search code examples
c#mongodbmongodb-querymongodb-.net-driver

With the mongoDB C# driver, how do I execute a runCommand with args?


I have a (for me) very complex mongo query, something like this:

public void GetData(ObjectId projectId, IList<ObjectId> users)
{
    var query = @"
    db.getCollection("users").aggregate([
    {
      $match: {
        projectId: projectId,
        userId: { $in: [...users] },
      },
    },
    {
      $group: {
        _id: { document: '$document', subject: '$subject' },
        context: { $push: { context: '$context' } },
        category: { $first: '$Category' }
      },
    }])";
    var items = this.Database.Db.RunCommand<Object>(query);
    ...
}

Here there is a projectId and a users parameter of this method. tries to found those documents where the projectId equals to the given value, and the userId is any of the given values. When I rewrite to C# fluent style it looks somehow like this:

public void GetData(ObjectId projectId, IList<ObjectId> users)
{
 var items = this.Database.Users
  .Aggregate()
  .Match(p => p.projectId  == projectId && users.Contains(p.user))
  /*
  .Group( p => new {document= p.Document, subject=p.Subject},
     // p => new { ???  }
     // ?????
     // )
  */
  .ToList();
  ...
}

Unfortunately, I am not experienced enough to continue writing the .Group(..) part (especially with the $push in it) and this is only a little part of a whole query with another Group()s and some Unwind()s and some Project()s later, therefore I decided to use it as-is, and apply the RunCommand().

But I do not know how to use the RunCommand() with arguments, or ... should I generate the query string included the current values instead?

How to solve the problem? What do you suggest me to continue? Thanks a lot in advance!


Solution

  • I would not recommend using RunCommand here, instead you can:

    1. Put $group stage arguments you want just as raw strings (.Group("..", "..")). Mongo driver allows implicit creating required arguments from string. See example with $match and $project stages here.
    2. You can always use AppendStage (see here). Where you can provide the whole $group stage as string. Something like: .AppendStage("{ '$group': { '_id' ..