繁体   English   中英

Mongo $projection,你能平放一个子文档数组吗?

[英]Mongo $projection, can you flat a sub-document array?

我想知道是否有一种方法可以通过投影嵌套子文档数组来“展平”,以便我可以使用它来根据类型对它的条目求和。

我的文档是这样的:

 { "order_id":12345, "date":8/17/2019, "payment":{ status:1, transactions:[ {type: 1, amount:200}, {type: 2, amount:250}, {type: 3, amount:50}, {type: 4, amount:50}, ] } } I would like to see if you can "flatten" it to something like this using $project: { "order_id":12345, "date":8/17/2019, "status":1, "type": 1, "amount":200 }, { "order_id":12345, "date":8/17/2019, "status":1, "type": 2, "amount":250 }, { "order_id":12345, "date":8/17/2019, "status":1, "type": 4, "amount":50 }, { "order_id":12345, "date":8/17/2019, "status":1, "type": 4, "amount":50 } }

我的主要目标是汇总类型 1 和 3 的所有交易以及类型 2 和 4 的所有交易的所有金额。

Any help would be great.

以下查询可以获得预期的输出:

db.check.aggregate([
    {
        $unwind:"$payment.transactions"
    },
    {
        $project:{
            "_id":0,
            "order_id":1,
            "date":1,
            "status":"$payment.status",
            "type":"$payment.transactions.type",
            "amount":"$payment.transactions.amount"
        }
    }
]).pretty()    

输出:

{
    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 1,
    "amount" : 200
}
{
    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 2,
    "amount" : 250
}
{
    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 3,
    "amount" : 50
}
{
    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 4,
    "amount" : 50
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM