SQL statements can be mapped to their corresponding MongoDB statement. Lets start with CRUD operations.
- CREATE:
CREATE TABLE customers ( id NOT NULL AUTO_INCREMENT, firstName Varchar(100), lastName Varchar(100), phone Varchar(20), PRIMARY KEY (id) )
MongoDB Equivalence for CREATE is a little different. Either we can create a collection or simply insert the data.
db.createCollection("customers");
db.customers.insertOne({ firstName: "Abebe", lastName: "Mulaw", phone: "09xxxxxxxx" })
2. READ: reading data from tables using both SQL and MongoDB statements is a little bit easier comparing to the other operations.
SELECT * FROM customers;
db.customers.find({})
If you we want to select specific fields,
SELECT firstName, lastName FROM customers;
db.customers.find({},{ firstName: 1, lastName: 1 })
If we want to use condition :
SELECT firstName, lastName FROM customers WHERE phone = '09xxxxxxx';
db.customers.find({ phone: '09xxxxxx' },{ firstName: 1, lastName: 1 })
3. UPDATE: During update in SQL and MongoDB, we can target a single row of data or multiple rows based on some criteria.
UPDATE customers SET firstName = "Tomas" WHERE phone = "09xxxxx"
db.customers.updateOne({ {phone: "09xxxxx"}, {$set: {firstName: "Tomas"}} })
Note: We can use MongoDB’s updateMany method to update multiple rows of data.
Example: If we want all customers to have the same phone number
db.customers.updateMany({ {}, {$set: {phone: "0911xxxxx"}} })
4. DELETE: To delete records, We can target single record or multiple records based on criteria’s.
DELETE FROM customers WHERE phone = '09xxxxxx'
db.customers.deleteOne({ {phone: "0911xxxxx"} })
We can also delete records with deleteMany method if there are records with same field.
db.customers.deleteMany({ {phone: "0911xxxxx"} })