猫鼬$ lookup计数参考

时间:2018-11-19 16:13:31

标签: node.js mongodb mongoose

这是我正在使用的MongoDB数据库的简化架构:

const podcastSchema: Schema = new Schema({
   name: { type: String, required: true },
   episodes: {
      type: [{
         title: { type: String, required: true },
      }],
      default: undefined
   }
},{
   timestamps: true
});

我添加了一个统计信息架构,基本上是播客每一集的收听次数:

const statisticSchema: Schema = new Schema({
   connectionIdentifier: { type: String, required: true },
   episode: { type: Schema.Types.ObjectId, ref: 'Podcast.Episodes' }
},{
   timestamps: true
});

现在,我需要为播客中的每一集加入(实际上是外部左加入),以便统计数据中的项目数,因此我可以得到这样的内容:

podcasts: {
   name: 'Lorem'
   episodes: [{
      title: 'Ipsum',
      played: 323
   },{
      title: 'Dolor',
      played: 12
   },
   ...
   ]
}

这是我的来源:

const episodes = await Podcast.aggregate([
   { $match: { _id: podcastId } }, {
      $lookup: {
         from: 'statistics',
         localField: 'episodes._id',
         foreignField: 'episode',
         as: 'resultingEpisodeArray'
      }
   },{
      $unwind: { path: '$resultingEpisodeArray', preserveNullAndEmptyArrays: true }
   },{
      $group: {
         _id: null,
         episode: { $push: '$episodes' },
         played: { $sum: 1 }
      }
   },{
      $project: {
         _id: '$episode._id',
         title: '$episode.
         played: '$played'
      }
   }
]);

但是它将所有播客聚合到一个播客中。 我在哪里失败?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

由于@AnthonyWinzlet的建议,我遇到了错误。我真的很需要在mongo上工作时忘记SQL。 出于知识的考虑,下面是修改后的代码,解决了我的问题:

const episodes = await Podcast.aggregate([
    { $match: { _id: podcastId } },
    { $unwind: '$episodes' },
    {
        $lookup: {
            from: 'statistics',
            localField: 'episodes._id',
            foreignField: 'episode',
            as: 'resultingEpisodeArray'
        }
    },
    {
        $project: {
            _id: '$episodes._id',
            title: '$episodes.title',
            played: { $size: '$resultingEpisodeArray' }
        }
    },
]);

再次,感谢安东尼为我指明了正确的方向!