In the Mongo shell, you can use the result of one query in another. For instance:
use database // the name of your database db.coll1.find({_id:{$nin:db.coll2.distinct("coll1_id")}})
Here the coll1 collection contains the _id field. Then you can check for any identifiers that are not in the coll2 list of the list of the coll1_id field. Thus, this is a way to clear two tables if you have entries in coll1 that do not have a link through the coll1_id field in coll2.
Another approach does the same:
use database
The first example is executed in one command, the second in two, but the concept is the same. Using the results of one query in another. Many different ways to do this. In addition, the .toArray () method can be useful for creating arrays if you are doing more than just using distinct ().
source share