【问题标题】:How to use raw MongoDB aggregation query in C#?如何在 C# 中使用原始 MongoDB 聚合查询?
【发布时间】:2021-09-24 11:03:27
【问题描述】:

我有以下 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 结果 = await _mongoDbContext.model.Aggregate(pipeline).ToListAsync();

【问题讨论】:

标签: c# mongodb asp.net-core aggregation-framework mongodb-.net-driver


【解决方案1】:

您可以通过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: {} }"); 

【讨论】:

  • 我可以使用原始 json 查询而不是 BsonDocument 吗?
  • AFAIK 不,您应该单独提供每个阶段,因此您应该将原始问题中的带有阶段的 bson 数组拆分为几个步骤(阶段一个步骤)。 $match、$group 等的单个阶段。
猜你喜欢
  • 2015-10-16
  • 2020-05-16
  • 2017-10-19
  • 2020-10-18
  • 2013-07-31
  • 1970-01-01
  • 2022-11-08
  • 2019-06-18
  • 1970-01-01
相关资源
最近更新 更多