如何将Mongodb结果放入数组中

  • 本文关键字:数组 结果 Mongodb mongodb
  • 更新时间 :
  • 英文 :


我的数据库MongoDB中有一个集合:

/*Order:*/
{
item: 'banana',
price: '2$',
order_type: INTERNATIONAL // There are 2 types: INTERNATIONAL and MAINLAND
}

我做了一个分组阶段,将所有类型为INTERNATIONAL和MAINLAND的订单分组,然后计算每种类型订单的总数。

db.getCollection('get_card_request').aggregate([
{$group: {
_id: '$order_type',
nbOfOrders: {$sum: 1}    
}}
])

我收到的结果是这样的:

/* 1 */
{
"_id" : "MAINLAND",
"nbOfOrder" : 3.0
}
/* 2 */
{
"_id" : "INTERNATIONAL",
"nbOfOrder" : 2.0
}

我想把小组赛结束后的结果放在一个数组中,但我不知道怎么做。我想得到这样的结果:

{
orderTypeCount: [
{
"_id" : "MAINLAND",
"nbOfOrder" : 3.0
},
{
"_id" : "INTERNATIONAL",
"nbOfOrder" : 2.0
}
],
... // the other fields
}

播放

db.collection.aggregate([
{
$group: {
_id: "$order_type",
nbOfOrders: {
$sum: 1
}
}
},
{
"$group": {
"_id": null,
"orderTypeCount": {
"$push": "$$ROOT"
}
}
},
{
$project: {
"_id": 0
}
}
])

我将上一个管道中的所有数据推送到一个数组变量中。

最新更新