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

编程入门 行业动态 更新时间:2024-10-27 07:18:38
本文介绍了如何在 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 聚合查询?

本文发布于:2023-11-22 09:38:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616917.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原始   如何在   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!