如何使用C#在Mongo中转换以下查询

时间:2017-05-29 23:40:05

标签: c# mongodb

我可以在Robomongo中运行它,但我不知道如何在C#

中执行此操作
db.mycollection.aggregate([
     {$match : { "Partner._id": {$in: ["acb123","def456"]}}}, 
     {$group : {_id: {status: "$Status"}, count: {$sum: 1}}}
])

1 个答案:

答案 0 :(得分:1)

您可以使用流畅的聚合,只需从JSON字符串中解析BsonDocuments:

var result = await mycollection.Aggregate()
       .Match(BsonDocument.Parse("{ 'Partner._id': {$in: ['acb123','def456']} }"))
       .Group(BsonDocument.Parse("{ _id: '$Status', count: {$sum: 1} }"))
       .ToListAsync();

或者您可以手动构建BsonDocuments:

var result = await mycollection.Aggregate()
   .Match(
      new BsonDocument {
         {"Partner._id", new BsonDocument("$in", new BsonArray(new []{"acb123","def456"}))}
      }
   ).Group(
      new BsonDocument {
         { "_id", "$Status" },  // thus you group by single field
         { "count", new BsonDocument("$sum", 1) }
      }
   ).ToListAsync();