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

Tuesday, 20 February 2024

EXISTS Condition in MongoDB

In MongoDB, there isn't a direct equivalent to the SQL EXISTS condition. However, you can achieve similar functionality using the exists operator within a query.


Suppose you have two collections: departments and employees, and you want to find all departments that have at least one employee. You can achieve this using MongoDB's aggregation framework.


Here's an example of how you can achieve this in MongoDB:


db.departments.aggregate([

  {

    lookup: {

      from: "employees",

      localField: "department_id",

      foreignField: "department_id",

      as: "employees"

    }

  },

  {

    match: {

      employees: { exists: true, ne: [] }

    }

  },

  {

    project: {

      department_name: 1

    }

  }

])


In this example:


- We use the lookup stage to perform a left outer join between the departments collection and the employees collection based on the department_id field.

- The match stage filters the documents to include only those where the employees array field exists and is not empty, effectively simulating the EXISTS condition.

- Finally, the project stage is used to project only the department_name field in the output.


This query will return all departments that have at least one employee associated with them. Adjust the field names and collection names according to your schema.

No comments:

Post a Comment

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