Lots of options:
1) Add document ID B to the array in document A (backward link). Now you can search for documents that do not have any elements in this array. Problem: the array may become too large for the size of the document if you have many cross-references.
2) Add a C collection that tracks links between A and B. It behaves like a join table.
3) Simple flag in 'referenced'. When you add B, mark all A that it refers to as "links". When you delete B, do a B check for all A to which it refers, and cancel any A that no longer has a link. Problem: May exit synchronization.
4) Use the map reduce by B to create a collection containing the identifiers of all A that any B refers to. Use this collection to mark all A that are referenced (after all the marks have been marked first). May use this to fix (3) periodically.
5) Put both types of documents in the same collection and use map reduce to emit _id and flag to say "in A" or "link B". In the reduction step, find any groups that have "in A" but not "refer to B".
...
source share