title: Counting data per user with mongo aggregation framework
body: <p>I have a collection, where each document contains user_ids as a property, which is an Array field. Example document(s) would be :</p>
  
  <pre><code>[{
    _id: 'i3oi1u31o2yi12o3i1',
    unique_prop: 33,
    prop1: 'some string value',
    prop2: 212,
    user_ids: [1, 2, 3 ,4]
  },
  {
    _id: 'i3oi1u88ffdfi12o3i1',
    unique_prop: 34,
    prop1: 'some string value',
    prop2: 216,
    user_ids: [2, 3 ,4]
  },
  {
    _id: 'i3oi1u8834432ddsda12o3i1',
    unique_prop: 35,
    prop1: 'some string value',
    prop2: 211,
    user_ids: [2]
  }]
  </code></pre>
  
  <p>My goal is to get number of documents per user, so sample output would be :</p>
  
  <pre><code>[
   {user_id: 1, count: 1},
   {user_id: 2, count: 3},
   {user_id: 3, count: 2},
   {user_id: 4, count: 2}
  ]
  </code></pre>
  
  <p>I've tried couple of things none of which worked, lastly I tried :</p>
  
  <pre><code>aggregate([
    { $group: {
      _id: { unique_prop: "$unique_prop"},
      users: { "$addToSet": "$user_ids" },
      count: { "$sum": 1 }
    }}
  ]
  </code></pre>
  
  <p>But it just returned the users per document. I m still trying to learn the any resource or advice would help.</p>