title: I need to count how many children orgs are assigned to a parent org in MongoDB
body: <p>I'm new to the MongoDB world. I'm trying to figure out how to count the number of children organizations assigned to a parent organization. I have documents that have this general structure:</p>
  
  <p>{</p>
  
  <pre><code>"_id" : "001",
      "parentOrganization" : {
      "organizationId" : "pOrg1"
      },
  "childOrganization" : {
      "organizationId" : "cOrg1"
      }
  </code></pre>
  
  <p>},</p>
  
  <p>{</p>
  
  <pre><code>"_id" : "002",
      "parentOrganization" : {
      "organizationId" : "pOrg1"
      },
  "childOrganization" : {
      "organizationId" : "cOrg2"
      }
  </code></pre>
  
  <p>},</p>
  
  <p>{</p>
  
  <pre><code>"_id" : "003",
      "parentOrganization" : {
      "organizationId" : "pOrg2"
      },
  "childOrganization" : {
      "organizationId" : "cOrg3"
      }
  </code></pre>
  
  <p>}</p>
  
  <p>Each document has a parentOrganization with an associated childOrganization. There may be multiple documents with the same parentOrganization, but different childOrganizations. There may also be multiple documents with the same parent/child relationship. Additionally, there may even be a case where a child org may associate with multiple parent orgs.</p>
  
  <p>I'm trying to group by parentOrganization and then count the number of unique childOrganization's associated with each parentOrganization, as well as display the unique id's. </p>
  
  <p>I have tried using an aggregation framework with $match and $group, but I'm still not getting into the child organization parts to count them. Here is what I'm currently attempting:</p>
  
  <p>var s1 = {$match: {"parentOrganization.organizationId": {$exists: true}}};</p>
  
  <p>var s2 = {$group: {_id: "$parentOrganization.organizationId", count: {$sum: "$childOrganization.organizationId"}}};</p>
  
  <p>db.collection.aggregate(s1, s2);</p>
  
  <p>My results are returning the parentOrganization, but my $sum is not returning the number of associated childOrganizations:</p>
  
  <p>/* 1 */
  {
      "_id" : "pOrg1",
      "count" : 0
  }</p>
  
  <p>/* 2 */
  {
      "_id" : "pOrg2",
      "count" : 0
  }</p>
  
  <p>I get the feeling it is a bit more complicated than my limited knowledge has access to at this time. What details am I missing in this query?</p>