title: Does mongodb provide for querying sub-document collections to find parent documents?
body: <p>I am in the process of learning node.js and mongodb. At the recommendation of many tutorials I am making use of mongoose to help with interacting with mongo. To complicate matters I have a significant RDMS background and am doing my best to fight my mind's desire to see mongodb through a SQL lense.</p>
  
  <p>Right now I am struggling with the concept of querying subdocuments. I have figured out how to query for a parent document based on a subdocument's property, but cannot figure out how to query for all parent documents (regardless of type) by directly querying child documents. To illustrate I have the following contrived example schemas:</p>
  
  <pre><code>// subdocument
  var CategorySchema = new Schema({
      name: { type: String, required: true }
  });
  
  var IpSchema = new Schema({
    ip_address: { type: String, required: true, index: true }
    ,categories: [CategorySchema]
  });
  
  var DomainSchema = new Schema({
    domain_name: { type: String, required: true, index: true }
    ,categories: [CategorySchema]
  });
  
  var ip = mongoose.model('Ip', IpSchema);
  var domain = mongoose.model('Domain', DomainSchema);
  var category = mongoose.model('Category', CategorySchema);
  </code></pre>
  
  <p>The above schema embeds a subdocument array of categories in each stored domain and ip document. Making it easy to retrieve domains and ips <strong><em>separately</em></strong> based on a category name, but difficult to retrieve all domains and ips associated with a particular category in a single shot. The below code outlines why I believe this:</p>
  
  <pre><code>category.find(function (err, tcs) {
      console.log(tcs); // contains an empty set because no categories stored here
  });
  
  ip.find({ 'categories.name' : req.params.category }, function(err, ips) {
      console.log(ips); // contains all parent documents w/ subdocument name
  });
  
  domain.find({ 'categories.name' : req.params.category }, function(err, ips) {
      console.log(ips); // contains all parent documents w/ subdocument name
  });
  </code></pre>
  
  <p>Now I could combine the results of the above queries, but that seems potentially brittle-- assuming that I reuse categories on an ever increasing number of documents. Does that leave me storing the category and then embedding a reference via a category id? That seems like it would increase churn when writing for the sake of optimizing for reads. Unfortunately my Googlefu has failed me in locating any tutorials / best practices for tagging schemes. It could also be that I am overly complicating things.</p>
  
  <p>What's the best way to retrieve disparate parent documents based on a shared subdocument?</p>