簡體   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