Skip to content

Instantly share code, notes, and snippets.

@jmn8718
Last active December 19, 2019 01:09
Show Gist options
  • Save jmn8718/fc5759bbcbf59d492967f1a2eb58ae5d to your computer and use it in GitHub Desktop.
Save jmn8718/fc5759bbcbf59d492967f1a2eb58ae5d to your computer and use it in GitHub Desktop.
Mongo DB query
db.getCollection('playlists').aggregate([
{ $unwind: '$videos' },
{
$lookup: {
from: 'videos',
let: { videoId: '$videos' },
pipeline: [
{ $match: { $expr: { $and: [{ $eq: ['$_id', '$$videoId'] }] } } },
{
$lookup: {
from: 'tags',
localField: 'tags',
foreignField: '_id',
as: 'tags'
}
},
{ $project: { tags: 1 } },
{ $unwind: '$tags' }
],
as: 'videos'
}
},
{ $unwind: { path: '$videos', preserveNullAndEmptyArrays: true } },
{
$group: {
_id: { _id: '$_id', title: '$title' },
videos: { $addToSet: '$videos._id' },
tags: { $addToSet: '$videos.tags.label' }
}
},
{
$project: {
_id: '$_id._id',
title: '$_id.title',
videos: '$videos',
tags: '$tags'
}
},
{ $match: { tags: { $in: ['mongo', 'node'] } } }
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment