What is Subquery?

A subquery is query inside an INSERT,UPDATE,SELECT,DELETE statements.

It can also be nested inside another subquery. It can be used anywhere an expression is allowed.

Example:

  1. SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) ;
  1. INSERT INTO CUSTOMERS_BKP SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS) ;

What is Join?

Join is a clause used to combine data from multiple tables based on related common values.

Types:

Inner join 

Self join

Outer join (left and right)

Examples:

  1. SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
  1. SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders LEFT OUTER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

What is MongoDB?

MongoDB is a NoSQL database which is used to store data in document form.

It is an OpenSource Document oriented Database. It uses JSON (JavaScript Object Notation) for displaying documents.  And BSON (Binary Object Notation) for storage and retrieval of data.

Features: 

  1. Flexible schema
  2. Heavy read
  3. Allows documents inside a document
  4. Array functionalities
  5. Support for CRUD operations with aggregation

How to perform Subquery and Join in MongoDB?

For subquery operation MongoDB provides aggregation and $lookup function.

We can easily use $lookup for subqueries and optimization.

Syntax:

{

$lookup:

{

from: ”name of collection to join”

localField: ”field from input document”

foreignField: “field from form <collection>”

as: “output field”

}

}

Examples:

SQL:

SELECT *,orders_det

FROM orders

where orders_det IN

(SELECT * FROM customers where custid=order.customerid)

MongoDB:

db.orders.aggregate([

{

$lookup:{

From:”customers”,

localField:”customerid”

foriengnField:”custid”

as:”orders_det”}

}

])

Leave a Reply