在对象数组中使用 $lookup [英] Use $lookup in an array of objects

查看:26
本文介绍了在对象数组中使用 $lookup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档结构如下:

<代码>{_id: 123,name: '我的播放列表',视频:[{视频ID:1},{视频ID:2},{视频 ID:3}]}

现在我想在视频集合中做一个 $lookup 来获取所有视频数据.最后,我需要一个这样的数据结构:

<代码>{_id: 123,name: '我的播放列表',视频:[{videoId:1, videoDetails:[{_id:1, title:'我的搞笑视频', views:123}]},{videoId:2, videoDetails:[{_id:2, title:'我的新视频', views:1234}]},{videoId:3, videoDetails:[{_id:3, title:'Another video', views:1236}]}]}

这在 MongoDB 3.2 和 $lookup 聚合中是否可行?

解决方案

假设具有详细信息的集合是 video.details 并且您在左连接是 _id:

<预><代码>[{$unwind:"$videos"},{$查找:{来自:"video.details",localField:"videos.videoId",外国字段:_id",如:详情"}},{$组:{_id:"$_id",姓名:{$first:"$name"},视频:{$推:{videoId:"$videos.videoId",视频详细信息:$详细信息"}}}}]

所以基本上你做你的查找,但稍后在 $group 阶段按照你喜欢的方式构建输出.如果您使用的是 MongoDB 3.3.4 或更高版本,则可能不需要第一个 $unwind 阶段(在此之前不允许对数组进行 $lookup).

I'm having the following document structure:

{
  _id: 123,
  name: 'My playlist',
  videos:[
   {videoId:1},
   {videoId:2},
   {videoId:3}]
}

Now I want to do a $lookup in the video collection to get all video data. At the end, I need a data structure like this:

{
  _id: 123,
  name: 'My playlist',
  videos:[
   {videoId:1, videoDetails:[{_id:1, title:'My funny video', views:123}]},
   {videoId:2, videoDetails:[{_id:2, title:'My new video', views:1234}]},
   {videoId:3, videoDetails:[{_id:3, title:'Another video', views:1236}]}]
}

Is this possible with MongoDB 3.2 and the $lookup aggregate?

解决方案

You can do it with something like this in MongoDB 3.2 assuming the collection that has the details is video.details and the field you are left-joining on is _id:

[  
   {  
      $unwind:"$videos"
   },
   {  
      $lookup:{  
         from:"video.details",
         localField:"videos.videoId",
         foreignField:"_id",
         as:"details"
      }
   },
   {  
      $group:{  
         _id:"$_id",
         name:{  
            $first:"$name"
         },
         videos:{  
            $push:{  
               videoId:"$videos.videoId",
               videoDetails:"$details"
            }
         }
      }
   }
]

So basically you do your lookup but later in a $group stage build the output the way you like it. you may not need the first $unwind stage if you are using MongoDB 3.3.4 or above (previous to that $lookup on arrays weren't allowed).

这篇关于在对象数组中使用 $lookup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆