I'm trying to understand how I should best set up a schema in MongoDB.
What I have is a many-to-many relationship, like this:
Playlist Document:
{
_id: '111',
title: 'some playlist',
songs: ['222', '333']
}
Song Document:
{
_id: '222',
album: 'some album',
artist: 'some artist'
}
A playlist can reference many songs and a song can belong to many playlists.
If I were to construct a query that searched the playlist collection for playlists containing a particular song id, wouldn't that be a terribly slow operation? It seems like the DB would need to iterate through the songs array of every single playlist to figure out what playlists to return.
The solution I arrived at is to construct my playlist documents like this:
{
_id: '111',
title: 'some playlist',
songs: {
222: true,
333: true
}
}
It seems like this is how I should do it (to me), and yet just about every example I can find uses arrays. Does Mongo do some magic internally when using arrays that makes them as fast to use as objects?