2

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?

1 Answer 1

2

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.

MongoDB supports indexes on fields that are arrays: http://docs.mongodb.org/manual/core/index-multikey/

From the documentation, it seems that MongoDB has no problem avoiding collection scans when searching for a specific value of an array, using the index instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I'd seen that kind of query done on arrays before but couldn't find info on how it actually worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.