简体   繁体   English

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

[英]How to use mongodb aggregation to transform document in nested array

My document looks like as shown below and I want to transform it using aggregation. 我的文档如下图所示,我想使用聚合对其进行转换。 Inside favourite_products I have product array and it has product_id corresponding to each shops. 在favourite_products内部,我具有产品数组,并且具有与每个商店相对应的product_id。 Now I just want product ids of all shops but sorted based on time. 现在,我只想要所有商店的产品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"
                        }
                    ]
                }
            ]

I want to transform it into this: 我想将其转换为:

"favourite_products"

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

Below returns time ordered documents of favourite_products.product.product_id 下面返回的时间顺序是favourite_products.product.product_id的订购文件

use project if you want the result as different documents. 如果您希望结果作为不同的文档,请使用项目。 or use group if you want the result as the array in one document. 如果希望将结果作为一个文档中的数组,请使用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'}
    }}  
])

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

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