我有以下 mongoDB 订单集合,我需要将它们分组到 C# 应用程序中:
[
{
_id: 123,
status: [{
Detail: 'Started',
Origin: 'France',
Last: true
}]
},
{
_id: 456,
status: [{
Detail: 'Received',
Origin: 'France',
Last: true
},{
Detail: 'Started',
Origin: 'Italy',
Last: false
}]
},
{
_id: 789,
status: [{
Detail: 'Started',
Origin: 'Rome',
Last: true
}]
},
{
_id: 123,
status: [{
Detail: 'Received',
Origin: 'Germany',
Last: true
},{
Detail: 'Started',
Origin: 'Spain',
Last: false
}]
}
]
我需要返回一个结构,其中包含这些订单的最后事件状态,按国家分组以及它们总和最后状态,如下所示:
[
{
France: {
Total: 2,
Started: 1,
Received: 1
},
Rome: {
Total: 1,
Started: 1,
Received: 0
},
Germany: {
Total: 1,
Started: 0,
Received: 1
}
}
]
您能帮我创建正确的聚合来创建此结果吗?
最佳答案
您可以使用以下聚合管道获得所需的结果:
db.orders.aggregate([
{
$unwind: "$status"
},
{
$group: {
_id: "$status.Origin",
Total: { $sum: 1 },
data: { $push: "$$ROOT" }
}
},
{
$project: {
Country: "$_id",
Total: 1,
Started: {
$size: {
$filter: {
input: "$data",
cond: { $eq: ["$$this.status.Detail", "Started"] }
}
}
},
Received: {
$size: {
$filter: {
input: "$data",
cond: { $eq: ["$$this.status.Detail", "Received"] }
}
}
}
}
}
])
这是一个 easy way使用 C# 和某种形式的类型安全来运行此聚合。
关于c# - MongoDB 组到 C# API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61143115/