MongoDB组到C#API

我有以下订单的mongoDB集合,我需要将它们分组在C#应用程序中:

    [
    {
        _id: 123,status: [{
                Detail: 'Started',Origin: 'France',Last: true
        }]
    },{
        _id: 456,status: [{
                Detail: 'Received',Last: true
                },{
                Detail: 'Started',Origin: 'Italy',Last: false
        }]
    },{
        _id: 789,Origin: 'Rome',{
        _id: 123,Origin: 'Germany',Origin: 'Spain',Last: false
                }]
    }
    ]

我需要从这些订单中返回一个具有最后活动状态的结构,并按国家/地区及其 sum 进行分组,如下所示:

    [
        {
            France: {
                Total: 2,Started: 1,Received: 1
            },Rome: {
                Total: 1,Received: 0
            },Germany: {
                Total: 1,Started: 0,Received: 1
            }
        }
    ]

您能帮助我创建正确的聚合来创建此结果吗?

sunjianing1234 回答:MongoDB组到C#API

您可以通过以下聚合管道来获得所需的结果:

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","Received"] }
                    }
                }
            }
        }
    }
])

这是一个easy way,可使用具有某种类型安全性的c#使用c#运行此聚合。

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

本文链接:https://www.f2er.com/2469560.html

大家都在问