下面是我正在处理的MongoDB数据库的简化模式:
const podcastSchema: Schema = new Schema({
name: { type: String, required: true },
episodes: {
type: [{
title: { type: String, required: true },
}],
default: undefined
}
},{
timestamps: true
});我为stats添加了一个模式,基本上是对播客的每一集进行监听计数:
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'
}
}
]);但是它把所有的播客集中在一个单一的节目中。我在哪里不及格?
谢谢你的帮助!
发布于 2018-11-20 09:25:14
感谢@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' }
}
},
]);再次感谢安东尼为我指明了正确的方向!
https://stackoverflow.com/questions/53378679
复制相似问题