MongoDB CRUD Operations
CREATE DATABASE IN mongoDB
MongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn't exist, otherwise it will return the existing database.
Syntax
syntax of create database is as follows - e.g. : use DataBaseName
Like :- use TestDB
Note :- CURD means create, read, update, and delete
1 :- CREATE COLLECTION
MongoDB createCollection(name, options) is used to create collection.
e.g :- db.createCollection("Student", { size: 2147483648 } )
2 :- CREATE OPERATIONS
syntax :- 1) db.collection.insertOne()
2) db.collection.insertMany()
Note:- (INSERT Data into Collection)
e.g :-1--) if insert one record
db.Student.insertOne( { name: "mohan", class: "BCA", rollno :5} );
e.g :- 2--) if insert multiple record at one time
db.Student.insertMany( [
{ name: "mohan", class: "BCA", rollno :5},
{ name: "sohan", class: "MBA", rollno :15},
{ name: "ram", class: "BBA", rollno :10},
{ name: "shyam", class: "MCA", rollno :25},
] );
3 :- READ OPERATIONS
syntax : db.collection.find(query, projection)
e.g :- db.Student.find()
e.g :-1) db.Student.find({ name: "shyam" })
e.g :-2) db.Student.find( { rollno : 5 } )
4 :- UPDATE OPERATIONS
syntax :- db.collection.update(selectQuery, udateQuery)
e.g :-1 )
db.Student.update({'name':'shyam'},{$set:{'name':'shyam kumar'}})
db.Student.update({'id':'2'},{$set:{'name':'Mohan kumar'}})
e.g :-2)
Note:- update class where rollno is greater than 10
db.Student.updateMany(
{ rollno : { $gt: 10 } },
{ $set: { "class" : 'PHD'} }
);
5 :- DELETE OPERATIONS
syntax :-1 ) db.collection.deleteOne()
:-2 ) db.collection.deleteMany()
e.g:- 1)
db.Student.deleteOne( { rollno : 4 } )