如何在 C# 中使用原始 MongoDB 聚合查询?

How to use raw MongoDB aggregation query in C#?

我有以下 mongoDB 查询在 mongoDB shell 中工作得很好,但想知道如何在 C# 中使用该查询?

db.collection.aggregate([{
        $match: {
            fieldName: "dsdsd",
            createdAt: {
                $gte: ISODate("2021-07-05T12:29:30.000+00:00"),
    
                $lte: ISODate("2021-07-15T12:29:30.000+00:00")
            }
        }
    }, {
        $group: {
            _id: {
                $dateToString: {
                    format: "%Y-%m-%d-%H",
                    date: "$createdAt"
                }
            },
            items: {
                $first: '$$ROOT'
            }
        }
    },{"$replaceRoot":{"newRoot":"$items"}}
    ,{"$sort":{"createdAt":-1}}
    
    ])

我想在 C# 中使用下面的原始查询,如下所示:

var pipeline = {
            $match: {
                fieldName: "dsdsd",
                createdAt: {
                    $gte: ISODate("2021-07-05T12:29:30.000+00:00"),
        
                    $lte: ISODate("2021-07-15T12:29:30.000+00:00")
                }
            }
        }, {
            $group: {
                _id: {
                    $dateToString: {
                        format: "%Y-%m-%d-%H",
                        date: "$createdAt"
                    }
                },
                items: {
                    $first: '$$ROOT'
                }
            }
        },{"$replaceRoot":{"newRoot":"$items"}}
        ,{"$sort":{"createdAt":-1}}
        

var result = await _mongoDbContext.model.Aggregate(pipeline).ToListAsync();

您可以通过 AppenStage

添加任何自定义阶段
collection
    .Aggregate()
    .AppendStage<BsonDocument>(BsonDocument.Parse("stage1"))
    .AppendStage<BsonDocument>(BsonDocument.Parse("stage2"))
    ..

        var pipeline = new EmptyPipelineDefinition<BsonDocument>()
            .AppendStage<BsonDocument, BsonDocument, BsonDocument>(BsonDocument.Parse("stage1"))
            .AppendStage<BsonDocument, BsonDocument, BsonDocument>(BsonDocument.Parse("stage2"));

        collection.Aggregate(pipeline).ToList();

更新: 您还可以对 db.runCommand 使用类似 shell 的语法(这更难):

MongoDB Enterprise mongos> db.runCommand({ aggregate: 'test', pipeline: [ {stage1_json}, {stage2_json} ], cursor: {}  })
...

其中 C# 等价物是:

var result = db.RunCommand<BsonDocument>("{ aggregate : 'test', pipeline:  [ {stage1_json}, {stage2_json} ], cursor: {} }");