I was wondering if there is a way to "flatten" though projection a nested sub-document array so I could use it to sum its entries based on type.
My document looks like this:
{ "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 } }
Primarily my goal is to aggregate all the amounts for transactions of type 1 & 3 and all the transactions with type 2 & 4.
Any help would be great.
The following query can get you the expected output:
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()
Output:
{
"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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.