MongoDb从简单文档到嵌套文档的聚合

时间:2019-03-04 13:16:21

标签: mongodb mongodb-query

我对MongoDb有问题。我需要嵌套到文档,但是我不能这样做。有人可以帮我吗?

在我的结构下面:

制造商:

{_id:'2323dewegfwef',
 id:1,
 name:'manufacturer'}

品牌:

{_id:'234234dsgfwef',
 id:1,
 name:'brand',
 products:[
             {_id:'23423sdfsdf',
              id:1,
              brandId:1,
              manufacturerId:1},

             {_id:'23423sdfsdf',
              id:2,
              brandId:1,
              manufacturerId:1}

           ]

}

我想合并两个集合并得出如下结果:

制造商:

{_id:345345regsfdg,
 id:1,
 name:'manufacturer',
 brands:[
             {_id:'234234dsgfwef',
              id:1,
              name:'brand1',
              products:[
                        {_id:'23423sdfsdf',
                         id:1,
                         brandId:1,
                         manufacturerId:1},

                        {_id:'23423sdfsdf',
                         id:2,
                         brandId:1,
                         manufacturerId:1}
                        ]
             },
             {_id:'234234dsgfwef',
              id:2,
              name:'brand2',
              products:[
                        {_id:'23423sdfsdf',
                         id:3,
                         brandId:2,
                         manufacturerId:1},

                        {_id:'23423sdfsdf',
                         id:4,
                         brandId:2,
                         manufacturerId:1}
                        ]
             }
       ]

}

尝试:

db.Manufacturer.aggregate([{$lookup:{from:'Brand',localField:'id',foreignField:'products.manufacturerId',as:'brands'}}])

我用$ lookup,$ group,$ push $ unwind尝试了多种组合... 但是我没有找到钥匙。

有帮助吗?

谢谢

0 个答案:

没有答案