title: Match Distinct Count from Multiple Arrays
body: <p>Now I have a collection <code>col</code> including docs like follows:</p>
  
  <pre><code>{
      "_id": 1,
      "shares": [{
              "fundcode": "000001",     
              "lastshares": 1230.20,
              "agencyno": "260",
              "netno": "260"
          },{
              "fundcode": "000002",
              "lastshares": 213124.00,
              "agencyno": "469",
              "netno": "001"
          },{
              "fundcode": "000003",
              "lastshares": 10000.80,
              "agencyno": "469",
              "netno": "002"
          }
      ],
      "trade": [{
              "fundcode": "000001",
              "c_date": "20160412",
              "agencyno": "260",
              "netno": "260",
              "bk_tradetype": "122",
              "confirmbalance": 1230.20,
              "cserialno": "10110000119601",
              "status": "1"
          },{
              "fundcode": "000002",
              "c_date": "20160506",
              "agencyno": "469",
              "netno": "001",
              "bk_tradetype": "122",
              "confirmbalance": 213124.00,
              "cserialno": "10110000119602",
              "status": "1"
          },{
              "fundcode": "000003",
              "c_date": "20170507",
              "agencyno": "469",
              "netno": "002",
              "bk_tradetype": "122",
              "confirmbalance": 10000.80,
              "netvalue": 1.0000,
              "cserialno": "10110000119602",
              "status": "1"
          }
      ]
  }
  </code></pre>
  
  <p>how can I realize a selection like the following sql using mongodb query?:</p>
  
  <pre><code>SELECT _id
  FROM col 
  WHERE col.shares.lastshares &gt; 1000 
    AND col.trade.agencyno = '469'
  GROUP BY _id
  HAVING COUNT(DISTINCT col.shares.fundcode) &gt; 2
    AND COUNT(DISTINCT col.trade.fundcode) &gt; 2
  </code></pre>
  
  <p>I tried the <code>$unwind</code>, <code>$groupby</code>, <code>$match</code> aggregate pipeline twice, but I did not get the right answer. Thanks for help.</p>