'Search by multiple aggregate lookup functions in MongoDB
I'm really struggling with how to be able to search via both Song and Artist name. Each are in their own collections and are connected via an ID. I have written the aggregate successfully, however the search term only filters via the Song name. Is there a way I can make this search by both song name and artist name. The second field I want to search by is the artistName on the project object. As an example of the new search that doesn't work - "Bust A Move Young MC", with "Young MC being" the artist name. In the current state, this simply returns 0 results. Any help would be much appreciated.
const searchTerm = 'Bust A Move'
let filter = []
const s = new RegExp(searchTerm.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'), 'gi')
filter = ['name'].map((field) => ({
[field]: s
}))
const agg = await Song.aggregate([
{
$lookup: {
from: 'artists',
localField: 'artist_id',
foreignField: 'artist_id',
as: 'artist'
}
},
{ $unwind: '$artist' },
{
$match: {
$or: filter
}
},
{
$project: {
_id: 1,
name: 1,
song_id: 1,
spotifyImg640: 1,
artist_id: '$artist.artist_id',
artistName: {
name: '$artist.name'
}
}
}
])
// Song Object
{
song_id: 1
name: "Bust A Move",
artist_id: 1
}
// Artist Object
{
artist_id: 1,
name: "Young MC"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
