c# - MongoDB 组到 C# API

标签 c# mongodb nosql aggregation mongodb-compass

我有以下 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# 和某种形式的类型安全来运行此聚合。

测试:https://mongoplayground.net/p/1x0wrJlTmJl

关于c# - MongoDB 组到 C# API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61143115/

相关文章:

java - MongoDB 查询用于聚合唯一字段上的动态文档

php - Cassandra:只选择最新的行

amazon-web-services - Golang DynamoDB UnmarshalListOfMaps 返回空数组

c# - Json.NET 基本类型 - 使用 Decimal 而不是 Double

c# - 如何使 protobuf-net 在反序列化时不考虑默认数组值

javascript - 如何将 MongoDB Server 添加为 Windows 包依赖项?

javascript - $not不执行$and操作

java - MongoDB-Java查询数据去掉_id只显示指定字段

c# - 我应该在 Page_Init 中以编程方式添加控制事件处理程序吗?

c# - 使用 Sharepoint API 获取 AD 域组的成员