Glaring mongodb weakness: nested arrays. What do?

This is a document for a YouTube-like site. This would be for a channel.

{
  _id: "1234",
  username: 'corvid',
  playlists: [{
    name: 'Learn to Develop Meteor',
    slug: 'learn-to-develop-meteor-345',
    videos: [{
      title: 'Publications and Subscriptions',
      description: 'Publish and subscribe data from the server',
      slug: 'publications-and-subscriptions'
    }, {
      title: 'Observable collections',
      description: 'Observe a live query as it changes',
      slug: 'observable-collections'
    }]
  }, {
    name: "Let's play Assassin's Creed: Black Flag",
    slug: 'assassins-creed-black-flag-123',
    videos: [{
      title: 'Part I: You are a pirate!',
      description: 'What shall we do with a drunken sailor?'
    }]
  }]
}

Now here’s the problem: Let’s say you want to publish a single video from this document.

Channels.find({
  username: 'corvid',
  'playlists.videos.title': 'Publications and Subscriptions'
}, {
  fields: { 'playlists.$.videos.$': 1 }
});

This always fails, but how are you supposed to get around it?

What I would do is keep playlists in a separate collection and use something like channel_id: channel._id to keep track of which channel they belong to. Same thing for videos in relation to playlists, or any relation for that matter. No reason to use nested objects when you can just query the objects you’re looking for based on the category _id.

You could make that channel_id key an array, so channel_id: [channel_one_id, channel_two_id] if the playlist/video is on multiple channels.

I would just normalize it, add channel_id to video document and put it in separate collection.
And if you go further with the like/follow relationships etc, maybe you end up migrating to neo4j as I am.

This is actual query from DB

2 Likes