How to use raw MongoDB aggregation query in C#?(如何在 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 聚合查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中使用原始 MongoDB 聚合查询?
基础教程推荐
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
