Search code examples
mongodbmongodb-querynosql-aggregation

find mongodb documents with matching UUIDs in separate collections


I have two collections (that include the following fields):

  • alertWizard.alertId (UI elements to CRUD alerts)
  • alertRules.id (technical elements that generate alerts)

Each alertWizard.alertId should match a single alertRules.id and vice versa.

I need to find all instances where there is not a matching alertRules.id for alertWizard.alertId in both collections.

But even a simple aggregation doesn't seem to be working (Using Studio3T aggregate tool):

use myMongoDb;
db.getCollection("alertsWizard").aggregate(
   [
      {
         "$match" : {
            "from" : "alertRules",
            "localField" : "$alertId",
            "foreignField" : "id",
            "as" : "matchingAlerts"
         }
      }
   ],
   {
      "allowDiskUse" : false
   }
);

I can see it pulling all the docs from the local collection, but fails to find any matches in the foreign/from collection. I have manually confirmed there are indeed matches, and are also some orphaned Wizards, and Rules.

Can someone help me at least understand Aggregation so I can see the matches. So then I can != the exceptions.


Solution

  • The stage is $lookupinstead of $match

    The documentation here

    db.getCollection("alertsWizard").aggregate(
       [
          {
             "$lookup" : {
                "from" : "alertRules",
                "localField" : "$alertId",
                "foreignField" : "id",
                "as" : "matchingAlerts"
             }
          }
       ],
       {
          "allowDiskUse" : false
       }
    );