本文介绍了如何在 C# 中使用原始 MongoDB 聚合查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 mongoDB 查询在 mongoDB shell 中运行良好,但想知道如何在 C# 中使用该查询?
I have the below mongoDB query working perfectly fine in mongoDB shell but wondering how to use that query in 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# 中使用以下原始查询,如下所示:
I want to use the below raw query in c# something like below:
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();
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 的语法(这更难):
UPDATE: you can also use a shell-like syntax for db.runCommand (which is harder):
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: {} }");更多推荐
如何在 C# 中使用原始 MongoDB 聚合查询?
发布评论