Insert Data in Database
Connection Database:-
import { MongoClient } from 'mongodb';
const url = 'mongodb://0.0.0.0:27017';
const client = new MongoClient(url);
const DbName = 'Student';
const DBConnection = async () =>{
let result = await client.connect();
let db = result.db(DbName);
return db.collection('StudentDetails');
export default DBConnection;
insert One data in Database:-
import Database from './connection.js'
const insert = async () => {
const db = await Database();
const result = await db.insertOne({name:'Demo',email:'
[email protected]'})
console.log(result.insertedId)
if(result.acknowledged)
{
console.log("Data insert.......");
}
}
insert();
insert Multiple data in Database:-
import Database from './connection.js'
const insert = async () => {
const db = await Database();
const result = await db.insertMany([
{name:'Demo0',email:'
[email protected]'},
{name:'Demo1',email:'
[email protected]'},
{name:'Demo2',email:'
[email protected]'}
])
if(result.acknowledged)
{
console.log("Data insert.......");
}
}
insert();
Read Data in Database
Read All data in Database:-
import Database from './connection.js'
const read = async () => {
const db = await Database();
const result = await db.find()
console.log(result.insertedId)
if(result.acknowledged)
{
console.log(result);
}
}
read();
Read Similar data in Database:-
import Database from './connection.js'
const read = async () => {
const db = await Database();
const result = await db.find({name:'Abcd'})
console.log(result.insertedId)
if(result.acknowledged)
{
console.log(result);
}
}
read();
Read Single data in Database:-
import Database from './connection.js'
const read = async () => {
const db = await Database();
const result = await db.findOne({name:'Abcd'})
console.log(result.insertedId)
if(result.acknowledged)
{
console.log(result);
}
}
read();
Update Data in Database
Update One Data in Database:-
import Database from './connection.js'
const update = async () => {
const db = await Database();
const result = await db.updateOne({name:'Demo1'},{$set:{name:"Radhi"}});
if(result.acknowledged)
{
console.log("Data update.......");
}
}
update();
Update Many Data in Database:-
import Database from './connection.js'
const update = async () => {
const db = await Database();
const result = await db.updateMany({name:'Demo1'},{$set:{name:"Radhi"}});
if(result.acknowledged)
{
console.log("Data update.......");
}
}
update();
Delete Data in Database
Delete One Data in Database:-
import Database from './connection.js'
const Delete = async () => {
const db = await Database();
const result = await db.deleteOne({name:'Radhi'});
if(result.acknowledged)
{
console.log("Data Delete.......");
}
}
Delete();
Delete Many Data in Database:-
import Database from './connection.js'
const Delete = async () => {
const db = await Database();
const result = await db.deleteMany({name:'Radhi'});
if(result.acknowledged)
{
console.log("Data Delete.......");
}
}
Delete();