Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Monday, 19 February 2024

EXCEPT Operator in MongoDB

In MongoDB, there isn't a direct equivalent of the EXCEPT operator found in SQL databases. However, you can achieve similar results using the aggregation framework, specifically using the $lookup stage to perform a left outer join between two collections. Here's how you can do it with an example:


Suppose you have two collections: employees and former_employees, both with similar structures, and you want to retrieve all documents from the employees collection that are not present in the former_employees collection.

Let's assume the following structures for the collections:

// employees collection

{

  "_id": ObjectId("..."),

  "employee_id": 1,

  "first_name": "John",

  "last_name": "Doe"

}


// former_employees collection

{

  "_id": ObjectId("..."),

  "employee_id": 2,

  "first_name": "Jane",

  "last_name": "Smith"

}


You can use the aggregation framework to achieve this:


db.employees.aggregate([

  {

    $lookup: {

      from: "former_employees",

      localField: "employee_id",

      foreignField: "employee_id",

      as: "former_employee"

    }

  },

  {

    $match: {

      former_employee: { $eq: [] } // Filter out documents where former_employee array is empty

    }

  },

  {

    $project: {

      former_employee: 0 // Remove the former_employee field from the output

    }

  }

])



Explanation of each stage:

1. $lookup: This stage performs a left outer join between the employees collection and the former_employees collection based on the employee_id field. It adds an array field former_employee to each document containing matching documents from the former_employees collection.


2. $match: This stage filters out documents where the former_employee array is empty, meaning there are no matches in the former_employees collection.


3. $project: This stage removes the former_employee field from the output documents to keep the result clean.


This aggregation pipeline will effectively retrieve all documents from the employees collection that are not present in the former_employees collection, simulating the behavior of the EXCEPT operator in SQL.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.