title: How to Find the Equivalent of Broken "Foreign Key" Relationships?
body: <p>I have two collections which are in what we would call a &quot;one to one relationship&quot; if this were a relational database. I do not know why one is not nested within the other, but the fact is that for every document in collection &quot;A&quot;, there is meant to be a document in collection &quot;B&quot; and vice versa.</p>
  <p>Of course, in the absence of foreign key constraints, and in the presence of bugs, sometimes there is a document in &quot;A&quot; which does not have a related document in &quot;B&quot; (or vice versa).</p>
  <p>I am new to MongoDB and I'm having trouble creating a query or script which will find me all the documents in &quot;A&quot; which do not have a related document in &quot;B&quot; (and vice versa). I guess I could use some sort of loop, but I don't yet know how that would work - I've only just started using simple queries on the RoboMongo command line.</p>
  <p>Can anyone get me started with scripts for this? I have seen &quot;<a href="https://stackoverflow.com/questions/24678749/verifying-reference-foreign-key-integrity-in-mongodb">Verifying reference (foreign key) integrity in MongoDB</a>&quot;,  but that doesn't help me. A bug has caused the &quot;referential integrity&quot; to break down, and I need the scripts in order to help me track down the bug. I also cannot redesign the database to use embedding (though I expect I'll ask why one document is not nested within the other).</p>
  <p>I have also seen &quot;<a href="https://stackoverflow.com/questions/29076006/how-to-find-intems-in-a-collections-which-are-not-in-another-collection-with-mon">How to find items in a collections which are not in another collection with MongoDB</a>&quot;, but it has no answers.</p>
  <h3>Pseudo-Code for a Bad Technique</h3>
  <pre><code>var misMatches = [];
  var collectionB = db.getCollection('B');
  var allOfA = db.getCollection('A').find();
  while (allOfA.hasNext()) {
      var nextA = allOfA.next();
      if (!collectionB.find(nextA._id)) {
          misMatches.push(nextA._id);
      }
  }
  </code></pre>