title: MongoDB : Group different fields with same common values
body: <p>I need to perform an aggregate on a mongodb collection. But I can't find the correct aggregation pipeline.</p>
  <p>In fact, I need to get IDs of different documents when <code>doc1.fieldTarget == doc2.fieldSource &amp;&amp; doc2.fieldTarget == doc3.fieldSource</code></p>
  <p>For example I want to find all documents when the target(docA) is the same than the source (of docB) and then verify if his target is the source of any other documents</p>
  <p>It's about finding the target server by port numbers.</p>
  <p>Sample docs:</p>
  <pre><code> [{
      _id: 11,
      portSource: 1,
      portTarget: 2,
      status:active
    },
    {
      _id: 22,
      portSource: 2,
      portTarget: 3
      status:passive
    },
    {
      _id: 33,
      portSource: 3,
      portTarget: 10
      status:active
    },
     {
      _id: 44,
      portSource: 3,
      portTarget: 5
      status:passive
    },
   {
      _id: 55,
      portSource: 5,
      portTarget: 7
      status:active
    },
   {
      _id: 66,
      portSource: 12,
      portTarget: 4
      status:active
    },
   {
      _id: 77,
      portSource: 4,
      portTarget: 16
      status:passive
    },
   {
      _id: 88,
      portSource: 4,
      portTarget: 246
      status:active
    },
   {
      _id: 99,
      portSource: 246,
      portTarget: 500
      status:active
    },
  ]
  </code></pre>
  <p><strong>My desired outpout:</strong></p>
  <pre><code>[
   {
    portSource: 1, portTarget: 10, sourceId : 11, targetId: 33
   },
   {
    portSource: 1, portTarget: 7, sourceId : 11, targetId: 55
   }
  ]
  </code></pre>
  <p>It looks like the segment addition postulate (AB+BC=AC).</p>
  <p>If there is a &quot;B&quot; then tell me that we have a connections between &quot;A&quot; and &quot;C&quot;</p>
  <p><strong>Note 1:</strong> The path can usually look like AB+BC+CD or more and the desired result is A-&gt;D as shown in the example with <code>id:11 &amp;&amp; id:55</code></p>
  <p><strong>Note 2:</strong> <code>id:66</code> isn't returned because the port 16 of <code>id:77</code> doesn't match to a potential &quot;C&quot;</p>
  <p><strong>Note 3:</strong> <code>id:66</code> isn't returned because <code>id:88</code> is not a passive &quot;B&quot;</p>
  <p>Thanks you !</p>