如何使用mongodb聚合来转换嵌套数组中的文档

时间:2017-07-12 08:56:56

标签: node.js mongodb express

我的文档如下所示,我想使用聚合对其进行转换。在favourite_products里面我有产品数组,并且每个商店都有product_id。现在我只想要所有商店的产品ID,但是根据时间排序。 :

"favourite_products": [
                {
                    "shop": {
                        "shop_id": "59465888f7babb000485574b",
                        "time": "2017-07-12T06:11:19.817Z"
                    },
                    "product": [
                        {
                            "product_id": "594c2d56f7afcf00043b1195",
                            "time": "2017-07-12T06:10:36.775Z"
                        },
                        {
                            "product_id": "594ac36c76de720004e819f6",
                            "time": "2017-07-12T06:11:19.817Z"
                        }
                    ]
                },
                {
                    "shop": {
                        "shop_id": "593acc24a2902d0004211f1f",
                        "time": "2017-07-12T06:12:59.372Z"
                    },
                    "product": [
                        {
                            "product_id": "594ac36c76de720004e819f6",
                            "time": "2017-07-12T06:12:59.372Z"
                        }
                    ]
                }
            ]

我想将其转化为:

"favourite_products"

 ["59465888f7babb000485574b",594c2d56f7afcf00043b1195","594ac36c76de720004e819f6","593acc24a2902d0004211f1f","594ac36c76de720004e819f6"]

1 个答案:

答案 0 :(得分:2)

以下返回favourite_products.product.product_id

的订购文件的时间

如果您希望将结果作为不同的文档,请使用项目。 如果您希望将结果作为一个文档中的数组,则使用group。

db['testing-aggregate'].aggregate([
    {$unwind:'$favourite_products'},
    {$unwind:'$favourite_products.product'},
    {$sort:{'favourite_products.product.time':1}}, // order by time. 1=ascending | -1=descending 
    //  {$project:{
    //      '_id':0, // exclude _id from output
    //      'favourite_products':'$favourite_products.product.product_id' // return only product_id
    //  }},
    {$group:{
        _id:null,
        product_id:{$push:'$favourite_products.product.product_id'}
    }}  
])