CRUD - MongoDB
Saurabh Kumar
Posted on June 28, 2020
This article contains the basics of MongoDB. A no-SQL database that stores your data in the form of the collection like Tables in SQL.
REQUIREMENT
- Basic Javascript - Promises, Error handling
- CMD
- ROBO3T GUI
- Your Native mongodb must be running.
Install -
- npm install mongodb
Then create a file(any_name.js) inside a Folder(Any_name):
Then inside of your "any_name.js" file :
const MongoDB = require("mongodb");
const MongoClient = MongoDB.MongoClient;
const databaseName = "first-project";
const connectionUrl = 'mongodb://127.0.0.1:27017';
MongoClient.connect(connectionUrl, { useUnifiedTopology: true }, (err, client) =>{
if(err){
console.log(errr)
}
This creates a database automatically
const db = client.db(databaseName);
INSERTION
INSERTION ONE
db.connection("User").insertOne({
name: "Saurabh",
age: 21
}).then((error) =>{
console.log(error)
}).catch((result) =>{
console.log(result)
})
INSERTION MANY
db.connection("User").insertMany([
{
name: "Saurabh",
age: 21
},
{
name: "Gaurav",
age: 21
}
]).then((error) =>{
console.log(error)
}).catch((result) =>{
console.log(result.ops)
})
.ops -> Is used to give you an array. This is not generally used in case of insertOne
as it only gives you only one object. This is generally used in Case of insertMany
READ
findOne
is used to find a particular data and find
is used to to extract multiple data -> Here we can use different methods. Like - toArray(), count etx.
db.collection('Task').findOne({
age: 12
}).then((output) =>{
console.log(output)
}).catch((error) =>{
console.log(error)
})
db.collection('User').find({age:45}).toArray((error, result) =>{
console.log(result)
})
UPDATE
Here, we use updateOne
to update a particular value. And $set
it takes a new value that we want in place of the previous data.
db.collection('User').updateOne({
name:"Saurabh Kumar"
},{
$set: {
name: "Gaurav Kumar"
}
}).then((result) =>{
console.log(result)
}).catch((error) =>{
console.log(error)
})
DELETE
Here, we use deleteMany
. And in the below wxample we put a constraint that is Age.
db.collection('User').deleteMany({
age: 45
}).then((result) => {
console.log(result.ops)
}).catch((error) => {
console.log(error)
})
})
Hope you like it :D
For more you can visit over here -
http://mongodb.github.io/node-mongodb-native/3.5/api/Collection
Complete Code over here -
Posted on June 28, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.